leetcode -- Unique Paths
2013-08-20 17:15
351 查看
1.DP bottom up
2.DP top down
ref:http://leetcode.com/2010/11/unique-paths.html
public int uniquePaths(int m, int n) { // Start typing your Java solution below // DO NOT write main() function int[][] steps = new int[m+2][n+2]; for(int i = 0; i < n + 2; i++){ steps[m+1][i] = 0; } for(int i = 0; i < m + 2; i++){ steps[i][n+1] = 0; } steps[m][n+1] = 1; for(int i = m; i >= 1; i--){ for(int j = n; j >= 1; j--){ steps[i][j] = steps[i+1][j] + steps[i][j+1]; } } return steps[1][1]; }
2.DP 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://leetcode.com/2010/11/unique-paths.html
相关文章推荐
- leetcode---62. Unique Paths
- Leetcode 62: Unique Paths
- [leetcode]Unique Paths
- [Leetcode] Unique Paths (Java)
- [LeetCode] Unique Paths-动态规划
- leetcode - Unique Paths
- leetcode(62). Unique Paths
- 【LeetCode】 062. Unique Paths
- leetcode62 Unique Paths
- [leetcode]Unique Paths
- 【Leetcode】Unique Paths (DP)
- 【LeetCode-面试算法经典-Java实现】【062-Unique Paths(唯一路径)】
- 【LeetCode】Unique Paths
- Leetcode62 Unique Paths
- leetcode-Unique Paths
- LeetCode-62-Unique Paths
- leetcode - Unique Paths
- [LeetCode] Unique Paths
- LeetCode 62 Unique Paths 解题报告
- LeetCode Unique Paths