该题目低级版跳台阶
尝试一
结果:通过
public class Solution {
private static int ways=0;
private static int target=0;
public int JumpFloorII(int target) {
/*把ways,target存为静态成员变量是为了方便使用*/
this.ways=0;
this.target=target;
/*用for循环把所有可能的步长都列出来*/
for(int i=1;i<=target;++i){
JumpFloor(0,i);
}
return ways;
}
public void JumpFloor(int sum,int length){
sum+=length;
if(sum==target){
/*找到一种方式*/
ways++;
return ;
}else if(sum>target){//失败
return ;
}
/*用for循环把所有可能的步长都列出来*/
for(int i=1;i<=target;++i){
JumpFloor(sum,i);
}
}
}
结论
- 递归可以做试探