70. Climbing Stairs

来源:互联网 发布:java逐个读取单词 编辑:程序博客网 时间:2024/06/05 08:41

https://leetcode.com/problems/climbing-stairs/description/
You are climbing a stair case. It takes n steps 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: Given n will be a positive integer.

解法一:

/**dp[n] = dp[n-1] + dp[n-2]*就是类似于斐波那契额数列嘛*/class Solution {public:    int climbStairs(int n) {        if(n <= 1)             return 1;        int dp[n];        dp[0] = 1;        dp[1] = 2;        for(int i = 2; i < n; i++) {            dp[i] = dp[i-1] + dp[i-2];        }        return dp[n - 1];    }};

解法二:
对空间进行进一步优化,我们只用两个整型变量a和b来存储过程值。

class Solution {public:    int climbStairs(int n) {        int a = 1;          int b = 1;          while(--n) {            int tmp = a;            a = a + b;  // 更新dp[n] = dp[n - 1] + dp[n - 2]            b = tmp;  // 更新dp[n - 1] = dp[n - 2]        }        return a;    }};
原创粉丝点击