1 题目
跨 N 级台阶,可以一次跨 1/2/3 级,但只能跨 1 次 3 级,一共有多少种跨法?
2 Java
注意使用 回溯正向递归,而非 动归正向迭代
这道题不知道怎么利用子问题加速
这种时候直接用回溯吧
import java.util.Scanner;
/**
* @classname XieCheng_Main1
* @description TODO 跨 N 级台阶,可以一次跨 1/2/3 级,但只能跨 1 次 3 级,一共有多少种跨法;注意使用 回溯正向递归,而非 动归正向迭代
* @author 张泽阳
* @date 2020/5/7 10:28
* @version 1.0
*/
public class XieCheng_Main1 {
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
int N = scanner.nextInt();
System.out.println(function(N));
}
public static int function(int N) {
helper(N, 0, true);
return ans;
}
static int ans = 0;
// three为true代表当前走到n级台阶,没有跨过3级台阶,还可以尝试一步跨3级
public static void helper(int N, int n, boolean three){
// if 是否记录路径
if(n >= N){
if(n == N){
ans++;
}
return;
}
// for 多路选择
if(three){
helper(N, n + 3, false);
}
helper(N, n + 2, three);
helper(N, n + 1, three);
}
}