【问题标题】:ArrayList, List数组列表,列表
【发布时间】:2017-02-24 13:52:41
【问题描述】:

当我试图解决子集问题时,我会编写这样的代码:

    public class Subsets {
        public List<List<Integer>> subsets(int[] nums) {
            List<List<Integer>> list = new ArrayList<>();
            Arrays.sort(nums);
            backtrack(list, new ArrayList<>(), nums, 0);
            return list;
        }
        public void backtrack(List<List<Integer>> list, ArrayList<Integer>temp, int[] nums, int start){
            list.add(temp);
            for(int i = start; i<nums.length;i++){
                temp.add(nums[i]);
                backtrack(list, temp, nums, i++);
                temp.remove(temp.size()-1);
            }        
        }
    }

输出是

[[],[],[],[],[],[],[],[]]

但正确答案应该是

[[3],[1],[2],[1,2,3],[1,3],[2,3],[1,2],[]]

当我像这样更改“回溯”代码时,答案是正确的:

public void backtrack(List<List<Integer>> list, List<Integer> temp, int[] nums, int start){
  list.add(new ArrayList(temp));
  for(int i = start; i<nums.length;i++){
   temp.add(nums[i]);
   backtrack(list, temp, nums, i+1);
   temp.remove(temp.size()-1);
   }
 }

我的问题:为什么我需要编写这样的代码:

    public void backtrack(List<List<Integer>> list, List<Integer> temp, int[] nums, int start){
        list.add(new ArrayList(temp));

而不是那个:

    public void backtrack(List<List<Integer>> list, ArrayList<Integer> temp, int[] nums, int start){
        list.add(temp);

【问题讨论】:

  • 感谢您的快速接受。我很高兴它对你有用!

标签: java algorithm


【解决方案1】:

这里:

list.add(new ArrayList(temp));

这个时间点创建一个 List 对象,其内容为temp

list.add(temp);

只需将现有temp 列表的引用添加到list

所以,在第二种情况下,当您稍后修改temp时,也会影响list的内容。

但除此之外:您的代码应该更难阅读/理解。在该方法中使用temp 参数没有意义。例如,您可以在方法中将temp 设为局部变量。无论如何,传入列表是。将其作为输入参数不会有任何好处;你只会增加混乱。

然后你改进你的命名 - 因为listtemp 真的没有告诉读者这些变量的意图用法是什么。

【讨论】:

    【解决方案2】:

    list.add(temp) 会将对同一 temp 对象的引用添加到列表中。稍后,您从中删除元素,直到它为空,算法以包含对同一空列表的多个引用的列表结束。

    使用new ArrayList(temp)(或者更好的是——类型安全的new ArrayList&lt;&gt;(temp))将创建一个与temp具有相同内容的新列表,所以稍后,当你从temp中删除元素时,这个列表是不受影响。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-12-05
      • 2014-07-04
      • 1970-01-01
      • 2012-03-07
      • 2018-01-06
      • 2014-05-03
      • 1970-01-01
      相关资源
      最近更新 更多