LeetCode 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?
方法一:递归
public int climbStairs2(int n) { if (n == 0) return 1; if (n < 3) return n; return climbStairs(n - 1) + climbStairs(n - 2); }
方法二:用临时变量保存前面两个数
public int climbStairs(int n) {
if (n <= 0)
return n == 0 ? 1 : 0;
int result = 0;
if (n < 3)
return n;
int pre = 1;
int last = 2;
for (int i = 3; i <= n; i++) {
result = last + pre;
pre = last;
last = result;
}
return result;
}
总结:方法一之所以能够优化为方法二是因为方法一计算了f(n-1)和f(n-2)(注意:这里f(n)指的是爬上第n阶的方法数),因此我们用两个临时变量保存就好了
与这题类似的另外一个题是:
There is a fence with n
posts, each post can be painted with one of thek
colors.
You have to paint all the posts such that no more than two adjacent fence posts have the same color.
Return the total number of ways you can paint the fence.
该题也是类似的原理
public class Solution {
/**
* @param n non-negative integer, n posts
* @param k non-negative integer, k colors
* @return an integer, the total number of ways
*/
public int numWays(int n, int k) {
if (n == 0 || k == 0)
return 0;
if (n < 3) {
return n == 1 ? k : k * k;
}
int pre = k;
int last = k * k;
int result = 0;
for (int i = 3; i <= n; n++) {
result = (k - 1) * pre + (k - 1) * last;
pre = last;
last = result;
}
return result;
}
}