题解 | #走方格的方案数#
走方格的方案数
https://www.nowcoder.com/practice/e2a22f0305eb4f2f9846e7d644dba09b
import java.util.*;
//不能走回头路,那么只能向下或者向右
//所以一个m*n规格棋盘的左上定点到右下定点的走法f(m,n)=f(m-1,n)+f(m,n-1)
//终止条件可以用数学归纳法得出,f(1,n)=n+1,f(m,1)=f(1,m)=m+1
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
while(sc.hasNext()){
int m = sc.nextInt();
int n = sc.nextInt();
System.out.println(f(m,n));
}
}
public static int f(int m,int n) {
int ways = 0;
if (m==1){
return n+1;
}
if (n==1){
return m+1;
}
return f(m-1,n)+f(m,n-1);
}
}
查看16道真题和解析
