版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_36783389/article/details/83351390
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?
Note: m and n will be at most 100.
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
很像那个数字直角三角形求走到最上面一个位置得到的最大和的那题
所以这题动态规划的状态转移方程也就很明确了,其实有些题目状态转移方程好找,但是赋初始值需要一些思考
这题只需要给dp[0][0] 赋值1后面的迭代就好了.
solution:
class Solution {
public int uniquePaths(int m, int n) {
if(m==0||n==0) //如果m==0或者n==0直接返回0就可以了因为这样的二维数组没有意义
return 0;
int[][] dp = new int[m+1][n+1];
dp[0][0] = 1; //初始化动态规划数组
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if(i==0&&j>0)
dp[i][j]+=dp[i][j-1]; //如果是第一行那么它只能是往右走得来的不能是往下走得来的
else if(j==0&&i>0)
dp[i][j]+=dp[i-1][j]; //如果是第一列那么它只能是往下走得来的不能是往右走得来的
else if(i!=0&&j!=0) //其它情况即可以由往右走得来也可以由往下走得来
dp[i][j] +=(dp[i-1][j]+dp[i][j-1]);
}
}
return dp[m-1][n-1]; //返回答案
}
}