【java-动态规划】62. Unique Paths

A robot is located at the top-left corner of a m x n grid (marked ‘Start’ in the diagram below).

The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked ‘Finish’ in the diagram below).

How many possible unique paths are there?
在这里插入图片描述

Above is a 7 x 3 grid. How many possible unique paths are there?

Example 1:

Input: m = 3, n = 2
Output: 3
Explanation:
From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:

  1. Right -> Right -> Down
  2. Right -> Down -> Right
  3. Down -> Right -> Right
    Example 2:

Input: m = 7, n = 3
Output: 28

Constraints:

1 <= m, n <= 100
It’s guaranteed that the answer will be less than or equal to 2 * 10 ^ 9.

class Solution {
    public int uniquePaths(int m, int n) {
        int[][] paths=new int[n][m];
        for(int i=0;i<n;i++)paths[i][0]=1;
        for(int i=0;i<m;i++)paths[0][i]=1;
        for(int i=1;i<n;i++) {
        	for(int j=1;j<m;j++)paths[i][j]=paths[i-1][j]+paths[i][j-1];
        }
        return paths[n-1][m-1];
    }
}

在这里插入图片描述
最左一列、最上一列是边界,全部初始化为1,表示在这两个方向上只能有一种移动方式,即向下或向右。paths[i][j]=paths[i-1][j]+paths[i][j-1](i!=0,j!=0):状态转移方程,表示paths[0][0]到paths[i][j]的路径数是由paths[i-1][j]+paths[i][j-1]不断累加的。

这就是动态规划的思想:把原问题分解为若干个子问题,子问题和原问题形式相同或类似,只不过规模变小了。

猜你喜欢

转载自blog.csdn.net/Dong__Ni/article/details/107139029