publicclassSolution { publicintMinCostClimbingStairs(int[] cost) { int n = cost.Length; int prev = 0, curr = 0; for (int i = 2; i <= n; i++) { int next = Math.Min(curr + cost[i - 1], prev + cost[i - 2]); prev = curr; curr = next; } return curr; } }
[sol2-JavaScript]
1 2 3 4 5 6 7 8 9 10
var minCostClimbingStairs = function(cost) { const n = cost.length; let prev = 0, curr = 0; for (let i = 2; i <= n; i++) { let next = Math.min(curr + cost[i - 1], prev + cost[i - 2]); prev = curr; curr = next; } return curr; };
[sol2-C++]
1 2 3 4 5 6 7 8 9 10 11 12 13
classSolution { public: intminCostClimbingStairs(vector<int>& cost){ int n = cost.size(); int prev = 0, curr = 0; for (int i = 2; i <= n; i++) { int next = min(curr + cost[i - 1], prev + cost[i - 2]); prev = curr; curr = next; } return curr; } };
[sol2-Golang]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
funcminCostClimbingStairs(cost []int)int { n := len(cost) pre, cur := 0, 0 for i := 2; i <= n; i++ { pre, cur = cur, min(cur+cost[i-1], pre+cost[i-2]) } return cur }
funcmin(a, b int)int { if a < b { return a } return b }
[sol2-Python3]
1 2 3 4 5 6 7 8
classSolution: defminCostClimbingStairs(self, cost: List[int]) -> int: n = len(cost) prev = curr = 0 for i inrange(2, n + 1): nxt = min(curr + cost[i - 1], prev + cost[i - 2]) prev, curr = curr, nxt return curr
[sol2-C]
1 2 3 4 5 6 7 8 9
intminCostClimbingStairs(int* cost, int costSize) { int prev = 0, curr = 0; for (int i = 2; i <= costSize; i++) { int next = fmin(curr + cost[i - 1], prev + cost[i - 2]); prev = curr; curr = next; } return curr; }
复杂度分析
时间复杂度:O(n),其中 n 是数组 cost 的长度。需要依次计算每个 dp 值,每个值的计算需要常数时间,因此总时间复杂度是 O(n)。