LeetCode 656: Coin Path

2710 단어
Note:
1. Find each steps lowest cost.
2. Find whether it could reach to end or not.
class Solution {
    public List cheapestJump(int[] A, int B) {
        int[] next = new int[A.length];
        long[] dp = new long[A.length];
        Arrays.fill(next, -1);
        List result = new ArrayList<>();
        for (int i = A.length - 2; i >= 0; i--) {
            long minCost = Integer.MAX_VALUE;
            for (int j = i + 1; j <= i + B && j < A.length; j++) {
                if (A[j] >= 0) {
                    long cost = A[i] + dp[j];
                    if (cost < minCost) {
                        minCost = cost;
                        next[i] = j;
                    }
                }
            }
            dp[i] = minCost;
        }
        
        int i = 0;
        for (; i < A.length && next[i] > 0; i = next[i]) {
            result.add(i + 1);
        }
        result.add(A.length);
        return i == A.length - 1 && A[i] >= 0 ? result : new ArrayList<>();
    }
}

 
전재 대상:https://www.cnblogs.com/shuashuashua/p/7645557.html

좋은 웹페이지 즐겨찾기