Solution for leetcode 120
https://leetcode.com/problems/triangle/
Draw a picture for better visualization and it can help me know the relationship between different indices.
Used dimension reduction for this problem
class Solution {
public int minimumTotal(List<List<Integer>> triangle) {
int n = triangle.size();
int size = triangle.get(n - 1).size();
int[] arr = new int[size];
for(int k = 0; k < size; k++){
arr[k] = triangle.get(n-1).get(k);
}
for(int i = n - 2; i >= 0; i--){
for(int j = 0; j <= i; j++){
List<Integer> curRow = triangle.get(i);
int curNum = curRow.get(j);
arr[j] = Math.min(arr[j], arr[j + 1]) + curNum;
}
}
return arr[0];
}
}
Thoughts on leetcode 576
https://leetcode.com/problems/out-of-boundary-paths/
During move x, the number of ways at position[i][j] = During move x - 1, the sum of the number of ways of the surrounding neighbours
We need to keep a record of the previous state for move x - 1 to calculate the new state for move x
Pay attention to the edge cases (add 1 directly if exceeds the bound)
Pay attention to overflow (use long type, mod 1000000000 + 7)
Solution for leetcode 576
class Solution {
public int findPaths(int m, int n, int maxMove, int startRow, int startColumn) {
int mod = 1000000000 + 7;
long [][] current = new long[m][n];
long [][] previous = new long[m][n];
for(int x = 0; x < maxMove; x++){
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
long left = j - 1 >= 0 ? previous[i][j-1] % mod : 1;
long right = j + 1 < n ? previous[i][j+1] % mod : 1;
long above = i - 1 >= 0 ? previous[i-1][j] % mod : 1;
long bottom = i + 1 < m ? previous[i+1][j] % mod: 1;
current[i][j] = (left + right + above + bottom) % mod;
}
}
for(int i1 = 0; i1 < m; i1++){
for(int j1 = 0; j1 < n; j1++){
previous[i1][j1] = current[i1][j1];
}
}
}
return (int)(current[startRow][startColumn]);
}
}