LeetCode题解:Climbing Stairs
2013-11-05 15:23
411 查看
Climbing Stairs
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个台阶的楼梯的走法等于:
ways(n) = ways(n-1) + ways(n-2)
恰好是Fibonacci数列。另外提一下,对Fibonacci数列的一个计算方法是,利用矩阵A=
/ \ | 1 1 | | 1 0 | \ /
的N次方来完成。而矩阵的N次方是可以用分而治之O(log N)实现的。这里不用了。
题解:
class Solution { public: int Fibonacci(int k) { if (k==0) return 0; int fib = 1; int prev1 = 0, prev2 = 1; for(int l = 1; l < k; ++l) { prev1 = prev2; prev2 = fib; fib = prev1 + prev2; } return fib; } int climbStairs(int n) { return Fibonacci(n); } };
相关文章推荐
- [LeetCode]题解(python):070-Climbing Stairs
- LeetCode题解:Climbing Stairs
- LeetCode题解:Climbing Stairs
- 【题解】【DP】【Leetcode】Climbing Stairs
- LeetCode 318. Maximum Product of Word Lengths 题解(C++)
- LeetCode题解:Count and Say
- leetcode题解-141. Linked List Cycle
- [LeetCode]题解(python):090-Subsets II
- leetcode题解-118. Pascal's Triangle && 119. Pascal's Triangle II
- [Leetcode] Climbing Stairs
- leetcode题解||Median of Two Sorted Arrays问题
- leetcode题解-20. Valid Parentheses
- LeetCode题解:Minimum Window Substring
- leetcode-climbing stairs
- LeetCode题解:Search a 2D Matrix
- LeetCode 之 Climbing Stairs
- [LeetCode 题解]: Permutation Sequcence
- LeetCode 57. Insert Interval 题解
- [LeetCode题解]455. Assign Cookies
- Leetcode题解14 26. Remove Duplicates from Sorted Array