格子的走法数量

题目:有x*y大小的格子,只能从左往右、从上往下走,问从左上到右下有多少种走法?
思路:类似于跳台阶,从最后一步倒推。有递归和非递归两种实现
分析:对于非递归可能有个问题,下图星号地方会被计算两次,增加复杂度
分析
实现:

package 走格子;

import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int x = sc.nextInt();
		int y = sc.nextInt();
		System.out.println(numPath2(x, y));
	}
	
	// 递归实现
	public static int numPath2(int x, int y) {
		if(x==1||y==1) return 1;
		return numPath2(x-1, y) + numPath2(x, y-1);
	}
	
	// 非递归实现
	public static int numPath1(int x, int y) {
		if(x==1||y==1) return 1;
		int[][] res = new int[x][y];
		for(int i=0;i<x;i++) res[i][0] = 1;
		for(int i=0;i<y;i++) res[0][i] = 1;
		for(int i=1;i<x;i++) {
			for(int j=1;j<y;j++) {
				res[i][j] = res[i-1][j] + res[i][j-1];
			}
		}
		return res[x-1][y-1];
	}
}

猜你喜欢

转载自blog.csdn.net/zyd196504/article/details/82873863
今日推荐