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?
思路很容易想,但是要尽量做到简化。
public class Solution {
public int uniquePaths(int m, int n) {
int[][] map =new int[m][n];
map[0][0]=1;
return find(m-1,n-1,map);
}
int find(int m,int n,int[][] map){
if(map[m][n]!=0){
return map[m][n];
}else{
if(m==0){map[m][n]= 1;}
else if(n==0){map[m][n]=1;}
else{
map[m][n]= find(m-1,n,map)+find(m,n-1,map);
}
return map[m][n];
}
}
}上面的方法是第一次写的,其实没有用到dp, 用的是 记忆化搜索(memory search),下面这种方法是第二次写用的dp:
public class Solution {
public int uniquePaths(int m, int n) {
if (m * n == 0) {
return 0;
}
int[][] result = new int[m][n];
for (int i = 0; i < m; i++) {
result[i][0] = 1;
}
for (int j = 1; j < n; j++) {
result[0][j] = 1;
}
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
result[i][j] = result[i - 1][j] + result[i][j - 1];
}
}
return result[m - 1][n - 1];
}
}
402

被折叠的 条评论
为什么被折叠?



