Climbing Stairs

来源:互联网 发布:沙丁鱼流量软件 编辑:程序博客网 时间:2024/04/30 21:55

题目:

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?


思想:

爬楼梯问题,采用动态规划来解决,当n=0时,只有一种办法,当n=1,时,也只有一种办法,当n>1时,有F(n)=F(n-1)+F(n-2),可采用递归来解决,但是时间和空间复杂度较高,LeetCode上会出现超时,不予通过。故采用空间换时间的办法,存储每一n对应的F(n)。


代码:

class Solution {public:int climbStairs(int n) {//采用递归long ret;if (n <= 0)return 0;if (n == 1 )return 1;elsereturn climbStairs(n - 1) + climbStairs(n - 2);}int climbStairs2(int n)//非递归{vector<long> ret;if (n <= 0)return 0;if (n == 1)return 1;ret.push_back(1);ret.push_back(1);for (int i = 2; i <=n ; i++){ret.push_back(ret[i - 1] + ret[i - 2]);}return ret[n];}};


0 0
原创粉丝点击