机试题-走方格的方案数(递归)

请计算n*m的棋盘格子(n为横向的格子数,m为竖向的格子数)沿着各自边缘线从左上角走到右下角,总共有多少种走法,要求不能走回头路,即:只能往右和往下走,不能往左和往上走。

 递归,因为只能下和右,所以一个点的方案是左点的方案和上点的方案加和。靠边的点方案只有一条路

import java.io.*;
import java.util.*;

public class Main {
    
    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        
     //  Scanner sc = new Scanner(System.in);
        String str = "";
       while((str = br.readLine()) != null) {
           String[] arr = str.split(" ");
           
           
             int a = Integer.parseInt(arr[0]);
              int b = Integer.parseInt(arr[1]);
           
           System.out.println(calc(a, b));
       }
    }
    
    public static int calc(int a, int b) {
        if (a == 0 || b == 0) {
            return 1;
        }
    
        return calc(a-1, b) + calc(a, b-1);
    }
}

 

你可能感兴趣的:(算法题,Java)