leetcode -- Unique Paths
1.DP bottom up
1 public int uniquePaths(int m, int n) { 2 // Start typing your Java solution below 3 // DO NOT write main() function 4 int[][] steps = new int[m+2][n+2]; 5 for(int i = 0; i < n + 2; i++){ 6 steps[m+1][i] = 0; 7 } 8 for(int i = 0; i < m + 2; i++){ 9 steps[i][n+1] = 0; 10 } 11 steps[m][n+1] = 1; 12 for(int i = m; i >= 1; i--){ 13 for(int j = n; j >= 1; j--){ 14 steps[i][j] = steps[i+1][j] + steps[i][j+1]; 15 } 16 } 17 return steps[1][1]; 18 }
2.DP top down
1 public int uniquePaths(int m, int n) { 2 // Start typing your Java solution below 3 // DO NOT write main() function 4 int[][] matrix = new int[m+2][n+2]; 5 for(int i = 0; i < m+2; i++){ 6 for(int j = 0; j < n+2; j++){ 7 matrix[i][j] = -1; 8 } 9 } 10 11 return dp(1, 1, m, n, matrix); 12 } 13 14 public int dp(int r, int c, int m, int n, int[][] matrix){ 15 if(r > m || c > n){ 16 return 0; 17 } 18 if(r == m && c == n){ 19 return 1; 20 } 21 if(matrix[r+1][c] == -1){ 22 matrix[r+1][c] = dp(r+1, c, m, n, matrix); 23 } 24 if(matrix[r][c+1] == -1){ 25 matrix[r][c+1] = dp(r, c+1, m, n, matrix); 26 } 27 28 return matrix[r+1][c] + matrix[r][c+1]; 29 }