Unique Paths
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?
Above is a 3 x 7 grid. How many possible unique paths are there?
Note: m and n will be at most 100.
[解题思路]
一维DP。 Step[i][j] = Step[i-1][j] + Step[i][j-1];
一维DP。 Step[i][j] = Step[i-1][j] + Step[i][j-1];
1 public class Solution { 2 public int uniquePaths(int m, int n) { 3 int[][] ways = new int[m+1][n+1]; 4 ways[0][1] = 1; 5 for(int i =1; i<= m; i++){ 6 for(int j = 1; j<=n; j++){ 7 ways[i][j] = ways[i-1][j]+ways[i][j-1]; 8 } 9 } 10 11 return ways[m][n]; 12 } 13 }
滚动数组
1 public class Solution { 2 public int uniquePaths(int m, int n) { 3 int row = m; 4 int col = n; 5 int[] paths = new int[col]; 6 for(int i = 0; i < col; i++){ 7 paths[i] = 1; 8 } 9 for(int i = 1; i < row; i++){ 10 for(int j = 1; j < col; j++){ 11 paths[j] = paths[j] + paths[j-1]; 12 } 13 } 14 return paths[col-1]; 15 } 16 }
bottom up
public class Solution { public int uniquePaths(int m, int n) { int[][] steps = new int[m+1][n+1]; for(int i = 0; i < n+1; i++){ steps[m][i] = 0; } for(int i = 0; i < m+1; i++){ steps[i][n] = 0; } // 此处的初始化是为了 让 steps[m-1][n-1] 为 1(即右下角的终点) steps[m-1][n] =1; for(int i = m-1; i>= 0; i--){ for(int j = n-1; j >=0; j--){ steps[i][j] = steps[i+1][j] + steps[i][j+1]; } } return steps[0][0]; } }
top down
public int uniquePaths(int m, int n) { // Start typing your Java solution below // DO NOT write main() function int[][] matrix = new int[m+2][n+2]; for(int i = 0; i < m+2; i++){ for(int j = 0; j < n+2; j++){ matrix[i][j] = -1; } } return dp(1, 1, m, n, matrix); } public int dp(int r, int c, int m, int n, int[][] matrix){ if(r > m || c > n){ return 0; } if(r == m && c == n){ return 1; } if(matrix[r+1][c] == -1){ matrix[r+1][c] = dp(r+1, c, m, n, matrix); } if(matrix[r][c+1] == -1){ matrix[r][c+1] = dp(r, c+1, m, n, matrix); } return matrix[r+1][c] + matrix[r][c+1]; }
ref : http://www.cnblogs.com/feiling/p/3270618.html
http://fisherlei.blogspot.com/2013/01/leetcode-unique-paths.html