1
2
3
|
【1】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? Note: Given n will be a positive integer. |
题意:你可以跳一阶台阶,也可以跳二阶台阶。问你跳上一个n阶的台阶总共有多少种跳法。
1
2
3
4
5
6
7
8
9
10
11
12
|
public class Solution {
public int climbStairs( int n) {
if (n== 1 || n== 2 ) return n;
int [] dp= new int [n+ 1 ];
dp[ 1 ]= 1 ;
dp[ 2 ]= 2 ;
for ( int i= 3 ;i<=n;i++){
dp[i]=dp[i- 1 ]+dp[i- 2 ];
}
return dp[n];
}
} |
PS:剑指offerP76和机试指南P157
1
2
|
【 2 】有一楼梯共m级,刚开始时你在第一级,若每次只能跨上一级或者二级,要走上m级,共有多少走法?注:规定从一级到一级有 0 种走法。
给定一个正整数 int n,请返回一个数,代表上楼的方式数。保证n小于等于 100 。为了防止溢出,请返回结果Mod 1000000007 的值。
|
JD笔试题,这里从1级到1级算0种。且初始你在第一级。
1
2
3
4
5
6
7
8
9
10
11
12
13
|
public class GoUpstairs {
public int countWays( int n) {
// write code here
int [] dp= new int [n+ 1 ];
dp[ 0 ]= 0 ;
dp[ 1 ]= 0 ;
dp[ 2 ]= 1 ;
dp[ 3 ]= 2 ;
for ( int i= 4 ;i<n+ 1 ;i++){
dp[i]=(dp[i- 1 ]+dp[i- 2 ])% 1000000007 ;
}
return dp[n];
}
|
PS:注意这里一级到一级不算。且你在一级。稍有不同。但是思路都是一样的。
本文转自 努力的C 51CTO博客,原文链接:http://blog.51cto.com/fulin0532/1903092