本文为senlie原创,转载请保留此地址:http://blog.csdn.net/zhengsenlie
Climbing Stairs
Total Accepted: 13319 Total
Submissions: 40778
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阶的楼梯,每次可以爬一阶或两阶,问爬到顶部有多少种方案
思路:dp,具体一点是斐波那契数列。f(i) = f(i-1) + f(i-2)
第i阶可以是从第i-2阶爬上来的,也可以是从第i-1阶爬上来的
进一步发现在迭代到第i阶时,我们只要保存前面的f(i-1)和f(i-2),
所以只要定义两个变量就可以,不用定义一个数组。
class Solution { public: int climbStairs(int n){ int f1 = 1, f2 = 2, f3; if(n == 1) return f1; if(n == 2) return f2; for(int i = 2; i < n; i++){ f3 = f1 + f2; f1 = f2; f2 = f3; } return f3; } };
Leetcode 动态规划 Climbing Stairs
时间: 2024-11-10 13:38:03