题目列表:
- 上楼梯
- 走格子
一、上楼梯
代码块:
import java.util.Scanner;
public class 上楼梯 {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
System.out.println(f(n));
}
//使用递归求总的走法,适合规模小的楼梯
static int mod = 10000007;
static int f(int n){
if(n == 0|| n == 1)return 1;
if(n == 2)return 2;
if(n == 3)return 4;
return f(n-1)%mod + f(n-2)%mod + f(n-3)%mod;
}
}
二、走格子
代码块:(两种解法:递归和递推)
import java.util.Scanner;
public class 走格子 {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int row = sc.nextInt();
int col = sc.nextInt();
long start = System.currentTimeMillis();
//System.out.println(f1(row, col));
//System.out.println("耗时:"+(System.currentTimeMillis()-start)+"ms");
System.out.println(f2(row, col));
System.out.println("耗时:"+(System.currentTimeMillis()-start)+"ms");
}
//使用递归求解(效率非常的低),相对抽象
static int f1(int x, int y){
if(x == 1 || y == 1)return 1;
return f1(x-1, y) + f1(x, y-1);
}
//使用递推求解(效率非常的高),相对具体
static int f2(int x, int y){
int[][]arr = new int[x][y];
//当只有一行的情况
for(int i = 0; i < y; i++){
arr[0][i] = 1;
}
//当只有一列的情况
for(int i = 0; i < x; i++){
arr[i][0] = 1;
}
//当多行多列的情况
for(int i = 1; i < x; i++){
for(int j = 1; j < y; j++){
arr[i][j] = arr[i-1][j]+arr[i][j-1];
}
}
// //打印数组arr
// for(int i = 0; i < x; i++){
// for(int j = 0; j < y; j++){
// System.out.print(arr[i][j]+" ");
// }
// System.out.println();
// }
return arr[x-1][y-1];
}
}