有n步台阶,每次只能上1步或者2步,一共有多少种方法
递归
public class Step{
@Test
public void test(){
System.out.println(f(50));
}
public int f(int n){
if(n < 1){
throw new IllegalArgumentException(n + "不能小于1")
}
if(n < 3){
return n;
}
return f(n-1)+ f(n-2);
}
}
循环迭代
public class Step{
@Test
public void test(){
System.out.println(f(50));
}
public int f(int n){
if(n < 1){
throw new IllegalArgumentException(n + "不能小于1")
}
if(n < 3){
return n;
}
int one = 2;
int two = 1;
int sum = 0;
for(int i=3; i<=n; i++){
sum = two + one;
two = one;
one = sum;
}
return sum;
}
}