Leetcode 120,576 (dp triangle)

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]);
   }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值