标签:
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?
第一反应,递归求解,貌似很简单。但是不幸,超时
public int climbStairs1(int n) { if (n == 1 || n == 2) { return n; } return climbStairs1(n-1) + climbStairs1(n-2); }
如果所示,标颜色的需要重复递归调用计算,所以动态规划的思想就是把重叠子问题存储下来,下次调用直接查表即可。比如在第一次递归调用时,n=3已经将结果计算出来,在n=4的时候就不需要就算了,上代码:
public int climbStairs(int n) { if (n == 0 || n == 1 || n == 2) { return n; } int[] r = new int[n+1]; r[1] = 1; r[2] = 2; for (int i = 3; i <= n; i++) { r[i] = r[i-1] + r[i-2]; } return r[n]; }
LeetCode-Climbing Stairs(爬楼梯问题)
标签:
原文地址:http://blog.csdn.net/my_jobs/article/details/43535179