首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >bestSum -动态规划

bestSum -动态规划
EN

Stack Overflow用户
提问于 2021-02-22 23:43:09
回答 1查看 223关注 0票数 1

我试图解决bestSum的问题,它基本上找到了与目标值相加的最小元素数量,下面的内容似乎很好,

示例输出,bestSum(10,新int[]{1,2,5})应该是pring [5,5]。

代码语言:javascript
复制
static List<Integer> bestSumNoDp(int target, int[] nums) {
    if (target == 0) return new ArrayList<>();
    if (target < 0) return null;

    List<Integer> shortest = null;
    for (Integer num : nums) {
        List<Integer> list = bestSumNoDp(target-num, nums);
        if (list != null) {
            list.add(num);
            if (shortest == null || shortest.size() > list.size())
                shortest = list;
        }
    }
    return shortest;
}

当我尝试实现DP版本时,我遇到了一个问题,我注意到当我打印缓存时,打印中有一个"Top",一个额外的元素被添加了,我不知道为什么,我做错了什么?

代码语言:javascript
复制
    static ArrayList bestSum(int target, int[] nums) {
        return bestSum(target, nums, new ArrayList[target+1]);
    }

    static ArrayList<Integer> bestSum(int target, int[] nums, ArrayList<Integer>[] cache) {
        if (target == 0) return new ArrayList<>();
        if (target < 0) return null;
        //System.out.println("Top - Target " + target + " Cache " + cache[target]); //Debugging

        if (cache[target] != null) return cache[target];
        
        ArrayList<Integer> shortest = null;
        for (Integer num : nums) {
            ArrayList<Integer> list = bestSum(target-num, nums, cache);
            if (list != null) {
                list.add(num);
                if (shortest == null || shortest.size() > list.size())
                    shortest = list;
            }
        }

//        cache[target] = null;//
//        cache[target] = (ArrayList<Integer>) shortest.clone(); //Didn't help
//        cache[target] = shortest;//Didn't help
        cache[target] = new ArrayList<>(shortest);//this one also didn't work but kept it
        //System.out.println("Bottom - Target " + target + " Cache " + cache[target]);//Debugging

        return shortest;
    }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-02-23 02:36:15

正如@btilly上面的评论所建议的,我需要这样做,

代码语言:javascript
复制
(cache[target] != null) return cache[target].clone();
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66325064

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档