一、Java
- class Solution {
- public int climbStairs(int n) { // f(1)=1, f(2)=2, f(3)=3, f(4)=5, f(0)=1
- int pre = 1, cur = 1;
- for (int i = 2; i <= n; i++) {
- cur += pre;
- pre = cur - pre;
- }
- return cur;
- }
- }
二、C++
- class Solution {
- public:
- int climbStairs(int n) {
- int pre = 1, cur = 1;
- for (int i = 2; i <= n; i++) {
- cur += pre;
- pre = cur - pre;
- }
- return cur;
- }
- };
三、Python
- class Solution:
- def climbStairs(self, n: int) -> int:
- pre, cur = 1, 1
- for i in range(2, n+1):
- cur, pre = cur + pre, cur
- return cur
四、JavaScript
- var climbStairs = function (n) {
- let pre = 1, cur = 1;
- for (let i = 2; i <= n; i++) {
- cur += pre;
- pre = cur - pre;
- }
- return cur;
- }
五、Go
- func climbStairs(n int) int {
- pre, cur := 1, 1
- for i := 2; i <= n; i++ {
- pre, cur = cur, pre + cur
- }
- return cur
- }