问题
I was going through this leetcode problem for going from top left to bottom right.
How many possible unique paths are there?
I was able to understand this method of dynamic programming by storing the result for every index.
public int uniquePaths(int m, int n) {
int count[][] = new int[m][n];
for (int i = 0; i < m; i++)
count[i][0] = 1;
for (int j = 0; j < n; j++)
count[0][j] = 1;
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
count[i][j] = count[i-1][j] + count[i][j-1]; //+ count[i-1][j-1];
}
}
return count[m-1][n-1];
// if (m == 1 || n == 1) return 1;
// return uniquePaths(m-1, n) + uniquePaths(m, n-1);
}
However, I found this solution which I am not able to understand.
public int uniquePaths(int m, int n) {
int[] dp = new int[n];
dp[0] = 1;
for (int i = 0; i < m; i++) {
for (int j = 1; j < n; j++) {
dp[j] += dp[j - 1];
}
}
return dp[n - 1];
}
Here is the link to the problem
Can somebody please explain the 2nd solution.
回答1:
In your first solution whole matrix is filled, but you can notice that each row is used only once in count[i][j] = count[i-1][j] + count[i][j-1]
.
So you can basically discard it after use. Second solution is doing exactly that. We can use only one row to perform all calculation.
When we fill it we can replace the code with count[0][j] = count[0][j] + count[0][j-1]
, which is basically count[0][j] += count[0][j-1]
.
Note that
for (int i = 0; i < m; i++)
count[i][0] = 1;
is useless, we always overwrite those cells.
And
for (int j = 0; j < n; j++)
count[0][j] = 1;
is equivalent to
dp[0][0] = 1;
for (int j = 1; j < n; j++) {
dp[0][j] += dp[0][j - 1];
}
which we already have as inner loop in second example.
回答2:
Basically, in second solution we are optimizing space complexity by utilizing the space used for saving calculation of previous row. Since, after calculation of values in current row, its value in jth
position will only be consumed by value in jth
position in next row.
So, dp[j] += dp[j - 1];
=> dp[j] = dp[j] + dp[j - 1]
=> dp value of jth column of current row = dp value at jth pos in prev row + dp value of j-1 th pos of current row
Here, value jth
column of previous row is being overwritten by value in jth
position of current row.
Thanks !
来源:https://stackoverflow.com/questions/55902034/all-possible-paths-from-top-left-to-bottom-right-of-a-mxn-matrix