Java solves different path problems

Java solves different path problems

01 Question

A robot is located in the upper left corner of a m x n grid (the start point is marked "Start" in the image below).

The robot can only move one step down or to the right at a time. The robot attempts to reach the lower right corner of the grid (labeled "Finish" in the image below).

How many different paths are there in total?

Example 1:

img

输入:m = 3, n = 7
输出:28

Example 2:

输入:m = 3, n = 2
输出:3
解释:
从左上角开始,总共有 3 条路径可以到达右下角。
1. 向右 -> 向下 -> 向下
2. 向下 -> 向下 -> 向右
3. 向下 -> 向右 -> 向下

Example 3:

输入:m = 7, n = 3
输出:28

Example 4:

输入:m = 3, n = 3
输出:6

hint:

  • 1 <= m, n <= 100
  • The question data ensures that the answer is less than or equal to2 * 109

02 Knowledge points

  • Two-dimensional array
  • DP (Dynamic Programming)

03 My solution

public class digui01 {
public static void main(String[] args) {
//测试数据
	uniquePaths(3, 7);
	
}
public static int uniquePaths(int m, int n) {
	 //通过二维数组来记录每个各格子的路径值
	 //路径值指到这个格子的方法数
	 int[][] grid=new int[m][n];
	 //因为每次出发一定会经过第一行或第一列某一格,所以设第一行和第一列格子上的值为1
	 for (int i = 0; i < m; i++) {
		grid[i][0]=1;
	}
	 for (int j= 0; j < n; j++) {
			grid[0][j]=1;
		}
	 //因为进入中间的格子只能从上方或者左边,所以中间格子的路径值为二者之和
	 for (int i = 1; i < grid.length; i++) {
			for (int j = 1; j < grid[0].length; j++) {
				grid[i][j]=grid[i-1][j]+grid[i][j-1];
			}
		}
	 //返回值为左下角的路径值
	 return grid[m-1][n-1];
 }
}

Guess you like

Origin blog.csdn.net/2302_77182979/article/details/135037447