0
点赞
收藏
分享

微信扫一扫

62. Unique Paths

禾木瞎写 2022-08-03 阅读 30


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?

62. Unique Paths_i++

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

Note: m and n will be at most 100.

思路:在只允许从左向右,从上到下移动的情况下,从mxn的矩阵(0,0)点,到(m-1,n-1)点,有多少路径。

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

for(int i=1; i<m;i++){
for(int j=1;j<n;j++){
array[i][j]=array[i-1][j]+array[i][j-1];
}
}

return array[m-1][n-1];
}
}

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

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


举报

相关推荐

0 条评论