FTPrep, 64 Valid Number
2017-09-11 06:58
211 查看
和前面的两道题差不多的DP类型的问题,而且都是走方格子。所以,这三道题就是不同的变形,只要把这个类型的搞定了就okay了。DP + 2D-array 的题就靠这62-64三道题就够了。
和设置障碍的那道题来说,这个在于第一行的处理要特别一点,因为还没有上面一行的格子可以判断。
其他的地方都差不多。
class Solution {
public int minPathSum(int[][] grid) {
if(grid.length==0 || grid[0].length==0) return 0;
int row = grid.length;
int col = grid[0].length;
int[] record = new int[col];
for(int i=0; i<col; i++){
if(i==0) record[i]=grid[0][0];
else record[i]=record[i-1]+grid[0][i];
} // fill up for the 1st row
for(int i=1; i<row; i++){
for(int j=0; j<col; j++){
if(j==0) record[j] += grid[i][j];
else record[j] = grid[i][j]+ Math.min(record[j], record[j-1]);
}
}
return record[col-1];
}
}
和设置障碍的那道题来说,这个在于第一行的处理要特别一点,因为还没有上面一行的格子可以判断。
其他的地方都差不多。
class Solution {
public int minPathSum(int[][] grid) {
if(grid.length==0 || grid[0].length==0) return 0;
int row = grid.length;
int col = grid[0].length;
int[] record = new int[col];
for(int i=0; i<col; i++){
if(i==0) record[i]=grid[0][0];
else record[i]=record[i-1]+grid[0][i];
} // fill up for the 1st row
for(int i=1; i<row; i++){
for(int j=0; j<col; j++){
if(j==0) record[j] += grid[i][j];
else record[j] = grid[i][j]+ Math.min(record[j], record[j-1]);
}
}
return record[col-1];
}
}
相关文章推荐
- FTPrep, 14 Longest Common Prefix
- FTPrep, 24 Swap Nodes in Pairs
- FTPrep, 39 Combination Sum
- FTPrep: 52 N-Queens II
- FTPrep: 55, Jump Game
- FTPrep, 83 Remove Duplicates from Sorted List
- FTPrep, 89 Gray Code
- FTPrep, 94 Binary Tree Inorder Traversal, TODO: recursive 所有/部分 遍历的模版
- FTPrep, 105 Construct Binary Tree from Preorder and Inorder Traversal
- FTPrep: 120 Triangle,可以归为 pathSum 路径和的这类题,因为用到了list/array,就是一道DP题。
- FTPrep, 127 Word Ladder, TODO,略难,没搞懂
- FTPrep, 25 Reverse Nodes in k-Group
- FTPrep, Combination Sum II
- FTPrep, 56 Merge Intervals
- FTPrep, 84 Largest Rectangle in Histogram
- FTPrep, 90 Subsets II
- FTPrep, 106 Construct Binary Tree from Inorder and Postorder Traversal
- FTPrep, 128 Longest Consecutive Sequence
- FTPrep, 10 container with most water
- FTPrep, 26 Remove Duplicates from Sorted Array