LeetCode 70 — Climbing Stairs(C++ Java Python)
2014-03-20 22:17
921 查看
题目:http://oj.leetcode.com/problems/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步到达顶端。
每次可以爬上1或2级。有多少种不同的方式到达顶端?
分析:
f(n)=f(n-1)+f(n-2)。自底向上。
C++实现:
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级。有多少种不同的方式到达顶端?
分析:
f(n)=f(n-1)+f(n-2)。自底向上。
C++实现:
class Solution { public: int climbStairs(int n) { int a[n + 1]; a[0] = 1; a[1] = 1; for(int i = 2; i <= n; ++i) { a[i] = a[i - 1] + a[i - 2]; } return a ; } };Java实现:
public class Solution { public int climbStairs(int n) { if (n == 0) { return 1; } int[] a = new int[n + 1]; a[0] = 1; a[1] = 1; for (int i = 2; i <= n; ++i) { a[i] = a[i - 1] + a[i - 2]; } return a ; } }Python实现:
class Solution: # @param n, an integer # @return an integer def climbStairs(self, n): a = [] a.append(1) a.append(1) for i in range(2, n + 1): a.append(a[i - 1] + a[i - 2]) return a感谢阅读,欢迎评论!
相关文章推荐
- [LeetCode] 012. Integer to Roman (Medium) (C++/Java/Python)
- [LeetCode] 014. Longest Common Prefix (Easy) (C++/Java/Python)
- [LeetCode] 017. Letter Combinations of a Phone Number (Medium) (C++/Java/Python)
- [LeetCode] 022. Generate Parentheses (Medium) (C++/Java/Python)
- LeetCode 33 — Search in Rotated Sorted Array(C++ Java Python)
- LeetCode 141 — Linked List Cycle(C++ Java Python)
- LeetCode 112 — Path Sum(C++ Java Python)
- Climbing Stairs | leetcode 70 【Java解题报告】
- LeetCode 67 — Add Binary(C++ Java Python)
- LeetCode 70 Climbing Stairs--Python实现
- LeetCode 12 — Integer to Roman(C++ Java Python)
- [LeetCode] 001. Two Sum (Medium) (C++/Java/Python)
- [LeetCode] 008. String to Integer (Easy) (C++/Java/Python)
- LeetCode 15 — 3Sum(C++ Java Python)
- LeetCode 144 — Binary Tree Preorder Traversal(C++ Java Python)
- LeetCode 20 — Valid Parentheses(C++ Java Python)
- 【LeetCode 70】Climbing Stairs(Python)
- LeetCode 34 — Search for a Range(C++ Java Python)
- LeetCode 28 — Implement strStr()(C++ Java Python)
- LeetCode 3 — Longest Substring Without Repeating Characters (C++ Java Python)