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?
T(n)=T(n−1)+T(n−2).
(Fn+1FnFnFn−1)=(1110)n+1.
可以转换成斐波那契数列进行解答
Code from http://my.oschina.net/u/811399/blog/141550
public class Solution {
public int climbStairs(int n) {
// Start typing your Java solution below
// DO NOT write main()
double s = Math.sqrt(5);
return (int)Math.floor(1/s*( Math.pow(0.5+s/2,(double)n+1)-Math.pow(0.5-s/2,(double)
}
}
Read full article from LeetCode - Climbing Stairs | Darren's Blog
By taking one step, there are T(n−1) distinct ways to finish the remaining. And by taking two steps, there are T(n−2) distinct ways to finish the remaining. That is, a recursion relationship can be identified:
This is exactly the definition of Fibonacci sequence.
public int climbStairs(int n) {
int f1 = 1, f2 = 2;
if (n == 1)
return f1;
if (n == 2)
return f2;
for (int i = 3; i <= n; i++) {
int f3 = f1 + f2;
f1 = f2;
f2 = f3;
}
return f2;
}
Another possible way is to leverage its matrix representation:Code from http://my.oschina.net/u/811399/blog/141550
public class Solution {
public int climbStairs(int n) {
// Start typing your Java solution below
// DO NOT write main()
double s = Math.sqrt(5);
return (int)Math.floor(1/s*( Math.pow(0.5+s/2,(double)n+1)-Math.pow(0.5-s/2,(double)
}
}
Read full article from LeetCode - Climbing Stairs | Darren's Blog
No comments:
Post a Comment