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
自己的代码:
方法一:
public static int uniquePaths(int m, int n) {
int[] result = new int[1];
uniquePathsHelper(result,m,n,0,0);
return result[0];
}
public static void uniquePathsHelper(int[] result,int m, int n,int i,int j) {
if(i > m || j > n) return;
if( i == m-1 && j == n-1) result[0]++;
uniquePathsHelper(result,m,n,i+1,j);
uniquePathsHelper(result,m,n,i,j+1);
}
1) 递归求解问题
2)不过,Time Limited Exceeded
别人的递归代码(依然对大数超时)
public int uniquePaths(int m, int n) {
return uniquePathsHelper(m - 1, n - 1);
}
private int uniquePathsHelper(int m, int n) {
if (m < 0 || n < 0) {
return 0;
} else if (m == 0 || n == 0) {
return 1;
} else {
return uniquePathsHelper(m - 1, n) + uniquePathsHelper(m, n - 1);
}
}
}
方法二:(动态规划)
class Solution {
public static 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 i=0;i<n;i++) dp[0][i] = 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];
}
}
Python代码:
def uniquePaths(m,n):
dp = [[1 for x in range(n)] for y in range(m)]
for i in range(1,m):
for j in range(1,n):
dp[i][j] = dp[i-1][j] + dp[i][j-1]
return dp[-1][-1]
if __name__ == '__main__':
m = 51
n = 9
result = uniquePaths(m,n)
print(result)