【问题标题】:Clone an ArrayList to another ArrayList does not work in DP将 ArrayList 克隆到另一个 ArrayList 在 DP 中不起作用
【发布时间】:2021-09-03 13:40:50
【问题描述】:

这是使用动态编程查找数组wordBank 的元素的最短串联以构造字符串Terget 的Java 代码。

示例:

输入: wordBank = {"ab", "c", "d", "abc", "ad"}, 目标 = "abcd"。

输出: {"abc", "d"}.

为此,我将元素组合作为 ArrayList 存储在 HashMap 中。 但是,hashMap 没有正确存储值,即,当我递归调用函数时,值会发生变化,尽管我在将 ArrayList 添加到地图之前已经克隆了它。

知道为什么会这样吗?

该代码适用于数组。

static ArrayList<String> bestConstruct(String target, String[] wordBank, HashMap<String, ArrayList<String>> map) {
    
    if(target.isEmpty())
    {
        return new ArrayList<String>();
    }
    
    if(map.containsKey(target))
        return map.get(target);
    
    ArrayList<String> shortestCombination = null;
    for (String word : wordBank) {
        
        if(target.startsWith(word)) {
            String newTarget = target.substring(word.length(), target.length());
            
            ArrayList<String> combination = bestConstruct(newTarget, wordBank, map);
            
            
            if(combination != null) {
                combination.add(word);
                
                if(shortestCombination == null || combination.size() < shortestCombination.size())
                    shortestCombination = (ArrayList<String>)(combination.clone());
            }
        }
    }
    map.put(target,  (ArrayList<String>) (shortestCombination.clone()));
    return shortestCombination;
}

【问题讨论】:

  • 数组列表不需要使用clone()。使用复制构造函数:new ArrayList&lt;&gt;(combination).
  • 我也做了同样的事,但还是不行
  • “当我递归调用函数时值会发生变化”你能举个例子吗?

标签: java arraylist dynamic-programming


【解决方案1】:

问题在于这些行之间的交互:

    if(map.containsKey(target))
        return map.get(target);

            ArrayList<String> combination = bestConstruct(newTarget, wordBank, map);
            
            
            if(combination != null) {
                combination.add(word);

如果您返回 memoized 列表,则表示您在克隆它之前对其进行了更新。

一般来说,不要依赖调用者“做正确的事”:如果您不想更新地图中的列表,请在返回之前自行复制:

    if(map.containsKey(target))
        return new ArrayList<>(map.get(target));

您可能还需要处理无法从词库构造字符串的情况。

【讨论】:

  • “不要依赖调用者做正确的事”是什么意思?你的意思是因为他们通过了引用?
  • @Elahe 我的意思是,如果您想确保调用者不会更改存储在地图中的列表,请不要给他们存储在地图中的列表。取消他们做错事的选择。
猜你喜欢
  • 2012-11-06
  • 1970-01-01
  • 1970-01-01
  • 2013-05-19
  • 1970-01-01
  • 1970-01-01
  • 2017-01-11
  • 2013-12-07
  • 2010-10-06
相关资源
最近更新 更多