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?
只计算爬楼方法:
java代码
int climbStairs(int n) {
if (n <= 1)
return 1;
int a = 1, b = 1, c = 1;
for (int i = 2; i <= n; ++i) {
c = a + b;
a = b;
b = c;
}
return c;
}
输出n层楼的爬楼方式
java代码
List<String> climbStairsWay(int n) {
List<String> res = new ArrayList<>();
if(n<=0)
return res;
List<String> last = new ArrayList<String>();
last.add("1");
if(n==1){
return last;
}
List<String> secondLast = new ArrayList<String>();
secondLast.add("1,1");
secondLast.add("2");
if(n==2) {
return secondLast;
}
for(int i=3;i<=n;i++) {
for(String temp : secondLast) {
res.add("1," + temp);
}
for(String temp : last) {
res.add("2," + temp);
}
if(i<n) {
last = secondLast;
secondLast = res;
res = new ArrayList<>();
}
}
return res;
}