Article Directory
Ready to start with the dynamic programming questions. Follow the steps honestly to think about the problem. Follow the four major steps of ACM clearance:
- 1. Determine the status
- 2. Transfer equation
- 3. Initial conditions and boundary conditions
- 4. Calculation order
1. Title description
Second, dynamic programming to solve problems
Analyze this is the most valuable dynamic programming problem.
One: Determine the status
- The last step comes from the previous column in the same column or the previous row in the same column.
- Sub-problem: the move from (1,1) to the end (m,n) is transformed into the move to (m-1,n) plus the move of (m,n-1)
- To determine the state, we open a two-dimensional array path[m][n] to represent the total number of paths from the start point to the end point.
2: Transfer equation
- if(m>=1,n>=1),path[m][n] = path[m-1][n]+path[m][n-1];
Three: Initial conditions and boundary conditions
- The initial conditions are
path[0][0] = 0,path[0][i]=1(i>=1),path[j][0]=1(j>=1)
. Because it is used to participate in calculations, although it cannot be obtained recursively. - The boundary condition is the value in the if statement, because m-1>=0 and n-1>=0 cannot cross the boundary. So we need to guarantee this.
Four: Calculation order - The order of calculation is the process of how we fill in the table. Where the subscript starts, we must ensure that the value involved in the recursion is calculated first in the recursion process.
With the above steps, we began to write the code:
class Solution {
public int uniquePaths(int m, int n) {
if(m<1||n<1){
return 0;
}
if(m==1||n==1)
return 1;
int[][] path = new int[m][n];
path[0][0]=0;
for(int i=0;i<n;i++){
//边界初始化
path[0][i]=1;
}
for(int i=0;i<m;i++){
//边界初始化
path[i][0] = 1;
}
for(int i=1;i<m;i++){
for(int j = 1;j<n;j++){
path[i][j] = path[i][j-1]+path[i-1][j];
}
}
return path[m-1][n-1];
}
}
Time complexity: O(m n); Space complexity: O(m n);
Three, optimize space complexity
class Solution {
public int uniquePaths(int m, int n) {
int[] cur = new int[n];
Arrays.fill(cur,1);
for (int i = 1; i < m;i++){
for (int j = 1; j < n; j++){
cur[j] += cur[j-1] ;
}
}
return cur[n-1];
}
}
Space complexity: O(N);