https://leetcode.com/problems/unique-paths/
第一眼看到这道题,就觉得该用递归做,递归解法如下:
public int uniquePaths(int m, int n) {
int[] total = new int[1];
helper(0, 0, total, m, n);
return total[0];
}
public void helper(int row, int column, int[] total, int desti, int destj){
if(row==desti && column==destj){
total[0]++;
return;
}
if(row>desti || column>destj) return;
helper(row+1, column, total, desti, destj);
helper(row, column+1, total, desti, destj);
}
递归解法超时,发现其实可以用DP做:
public int uniquePaths(int m, int n){
int[][] paths = new int[m][n];
paths[0][0]=1;
for(int i=0; i<m; i++){
for(int j=0; j<n; j++){
if(i==0 && j==0) continue;
else if(i==0) paths[i][j] = paths[i][j-1];
else if(j==0) paths[i][j] = paths[i-1][j];
else paths[i][j] = paths[i-1][j]+paths[i][j-1];
}
}
return paths[m-1][n-1];
}
后来看了大神的文章,发现其实一维数组就能解决,可以节省空间,但是时间复杂度是一样的,解法如下:
public int uniquePaths(int m, int n){
int[] paths = new int[n];
paths[0] = 1;
for(int i=0; i<m; i++){
for(int j=1; j<n; j++){
paths[j] = paths[j]+paths[j-1];
}
}
return paths[n-1];
}
总结:在用递归时,都应该考虑是否能用DP解,并且,在DP时,要尽量减少空间复杂度。