//到达n阶只可能来自n-1和n-2,所以f(n)=f(n-1)+f(n-2)
//1 2 3 5 8 13
int climbStairs(int n){
if (n == 1)
return 1;
if (n == 2)
return 2;
int sta = 0, sta1 = 1, sta2 = 2;
for (int i = 3; i <= n; i++) {
sta = sta1 + sta2;
sta1 = sta2;
sta2 = sta;
}
return sta;
}
class Solution:
def climbStairs(self, n: int) -> int:
if n == 1:
return 1
if n == 2:
return 2
stat1, stat2 = 1, 2
for i in range(3, n+1):
sum = stat1 + stat2
stat1 = stat2
stat2 = sum
return sum
/*
Date: 2019/11/25
Author: xzping
function: leetcode70 Climb Stairs
*/
package main
import "fmt"
func ClimbStairs(n int) int {
if n == 1 {
return 1
}
if n == 2 {
return 2
}
return ClimbStairs(n-1) + ClimbStairs(n-2)
}
func ClimbStairs2(n int) int {
if n == 1 {
return 1
}
if n == 2 {
return 2
}
var sta, sta1, sta2 int = 0, 1, 2
for i := 3; i <= n; i++ {
sta = sta1 + sta2
sta1 = sta2
sta2 = sta
}
return sta
}
func main() {
var n int
n = ClimbStairs(9)
fmt.Println("n = ", n)
n = ClimbStairs2(9)
fmt.Println("n = ", n)
}