题目列表:
- 上楼梯
- 走格子
- 硬币表示
- 合法括号
- 水洼数目
一、上楼梯
代码块:
/*
题目描述:
有个小孩正在上楼梯,楼梯有n阶台阶,小孩一次可以上1阶、2阶、3阶。
请实现一个方法,计算小孩有多少种上楼的方式?
为了防止溢出,请将结果 Mod 10000007
给定一个正整数int n,请返回一个数,代表上楼的方式数。
*/
/*
思路:(自下而上——想)
比如:把问题的规模往小的方面想:
上一节楼梯会有几种走法,上两节楼梯有几种走法,一次类推到一个大问题
*/
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)return 0;
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;
}
}
二、走格子
代码块:(两种解法:递归和递推)
/*
题目描述:
有一个x*y的网格,一个机器人只能走格点且只能向右或向下走,要从左上角走到右下角。
请设置一个算法,计算机器人有多少种走法?
给定两个正整数int x,int y,请返回机器人的走法数目,保证x+y小于等于12.
*/
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