码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 656: Coin Path

时间:2017-10-10 16:37:12      阅读:113      评论:0      收藏:0      [点我收藏+]

标签:class   array   for   log   color   return   note   res   new   

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

 

LeetCode 656: Coin Path

标签:class   array   for   log   color   return   note   res   new   

原文地址:http://www.cnblogs.com/shuashuashua/p/7645557.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!