内容:
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层阶梯情况下,走到顶端的路径种数(要求每次只能上1层或者2层阶梯)。
这是一个动态规划的题目:
n = 1 时 ways = 1;
n = 2 时 ways = 2;
n = 3 时 ways = 3;
…
n = k 时 ways = ways[k-1] + ways[k-2];
class Solution {
public:
int climbStairs(int n)
{
int stepone = 0;
int steptwo = 1;
int sum = 0;
for(int i = 0;i<n;i++)
{
sum = stepone + steptwo;
stepone = steptwo;
steptwo = sum;
}
return sum;
}
};