Problem:
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?
Explanation:
在一个m*n的格子中,机器人在左上方,终点在右下方,机器人每次只能向下或向右走一步,有几种走法到终点。
My Thinking:
定义dp[i][j]为到第i,j格的路径数量,则满足dp[i][j]=dp[i-1][j]+dp[i][j-1],由于只能往下或往右走,因此第一排或第一列的路径数一定是1。
My Solution:
class Solution {
public int uniquePaths(int m, int n) {
int dp[][]=new int[m][n];
for(int i=0;i<m;i++)
dp[i][0]=1;
for(int j=0;j<n;j++)
dp[0][j]=1;
for(int i=1;i<m;i++){
for(int j=1;j<n;j++){
dp[i][j]=dp[i-1][j]+dp[i][j-1];
}
}
return dp[m-1][n-1];
}
}
Optimum Thinking:
可以使用一维数组dp[i]来表示某一列第i个格子的路径数量,按行更新
Optimum Solution:
class Solution {
public int uniquePaths(int m, int n) {
int dp[]=new int[m];
for(int i=0;i<m;i++)
dp[i]=1;
for(int j=1;j<n;j++){
for(int i=1;i<m;i++){
dp[i]=dp[i-1]+dp[i];//dp[i]相当于上面格子,dp[i-1]相当于左边格子
}
}
return dp[m-1];
}
}