LeetCode: Climbing Stairs

来源:互联网 发布:js获取数组前3个值 编辑:程序博客网 时间:2024/05/08 02:44

#include<iostream>#include<algorithm>#include<string>using namespace::std;class Solution {public://iteration int climbStairs(int n) {        if(n == 0 || n == 1)            return 1;        int steps_n_2 = 1;        int steps_n_1 = 1;        for(int i = 2; i <= n; ++i) {            int steps_n = steps_n_1 + steps_n_2;            steps_n_2 = steps_n_1;            steps_n_1 = steps_n;        }        return steps_n_1;    }//recursionint climbStairs_2(int n) {        if(n == 0 || n == 1)            return 1;elsereturn climbStairs_2(n - 1) + climbStairs_2(n - 2);    }//print all ways void printPath(int n, string result){if(n == 0){cout<<result<<endl;}if(n >= 1){//result = result + "1";//mistake!, see belowprintPath(n - 1, result + "1");//key point! we can't modify result value because if we do so then in the current function, the result is not correct}if(n >= 2){printPath(n - 2, result + "2");}}};int main(){Solution ss;string tmp;ss.printPath(10, tmp);}

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?

Round 2:

class Solution {public:    int climbStairs(int n) {        int steps[n+1];        steps[0] = 1;        steps[1] = 1;        for(int i = 2; i <= n; i++)        {            steps[i] = steps[i-1] + steps[i-2];        }        return steps[n];    }};


原创粉丝点击