70 Climbing Stairs

https://leetcode.com/problems/climbing-stairs/#/description

You are climbing a stair case. It takesnsteps to reach to the top.

Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

Note:Givennwill be a positive integer.

分析及代码

状态转移方程:

path[i] = path[i - 1] + path[i - 2]

代码:


public int climbStairs(int n) {
    if(n < 1) {
        return 0;
    }
    int[] path = new int[n + 1];
    path[0] = 1;
    path[1] = 1;
    for(int i = 2; i <= n; i++) {
        path[i] = path[i - 1] + path[i - 2];
    }
    return path[n];
}

O(n)

results matching ""

    No results matching ""