Note:

1. Find each steps lowest cost.

2. Find whether it could reach to end or not.

class Solution {
    public List<Integer> cheapestJump(int[] A, int B) {
        int[] next = new int[A.length];
        long[] dp = new long[A.length];
        Arrays.fill(next, -1);
        List<Integer> 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<>();
    }
}

 

posted on 2017-10-10 14:45  keepshuatishuati  阅读(266)  评论(0编辑  收藏  举报