> For the complete documentation index, see [llms.txt](https://protegejj.gitbook.io/oj-practices/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://protegejj.gitbook.io/oj-practices/chapter1/dynamic-programming/746-min-cost-climbing-stairs.md).

# 746     Min Cost Climbing Stairs

## 746. [Min Cost Climbing Stairs](https://leetcode.com/problems/min-cost-climbing-stairs/description/)

## 1. Question

On a staircase, the`i`-th step has some non-negative cost`cost[i]`assigned (0 indexed).

Once you pay the cost, you can either climb one or two steps. You need to find minimum cost to reach the top of the floor, and you can either start from the step with index 0, or the step with index 1.

**Example 1:**

```
Input: cost = [10, 15, 20]

Output: 15

Explanation:
Cheapest is start on cost[1], pay that cost and go to the top.
```

**Example 2:**

```
Input: cost = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1]

Output: 6

Explanation:
Cheapest is start on cost[0], and only step on 1s, skipping cost[3].
```

**Note:**

1. `cost`will have a length in the range`[2, 1000]`.
2. Every`cost[i]`will be an integer in the range`[0, 999]`.

## 2. Implementation

**(1) DP**

思路: 由于我们可以选择从index 0或者index 1开始，所以对于位置i来说，产生的cost有两种情况，状态转移为:

f(i) = cost(i) + min(f(i - 1), f(i - 2)); 其中f(i)表示在位置i上最小的cost

```java
class Solution {
    public int minCostClimbingStairs(int[] cost) {
        if (cost == null || cost.length == 0) {
            return 0;
        }

        int n = cost.length;
        int[] dp = new int[n + 1];
        dp[0] = cost[0];
        dp[1] = cost[1];

        for (int i = 2; i <= n; i++) {
            int curCost = i == n ? 0 : cost[i];
            dp[i] = curCost + Math.min(dp[i - 1], dp[i - 2]);
        }
        return dp[n];
    }
}
```

## 3. Time & Space Complexity

**DP：**&#x65F6;间复杂度O(n), 空间复杂度O(n)
