I have the following code for the problem "Given a set of distinct integers, return all possible subsets. If nums = [1,2,3]
, a solution is [ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ]
."
public class Solution {
public ArrayList<ArrayList<Integer>> subsets(int[] num) {
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
if(num == null || num.length == 0) {
return result;
}
ArrayList<Integer> list = new ArrayList<Integer>();
Arrays.sort(num);
subsetsHelper(result, list, num, 0);
return result;
}
private void subsetsHelper(ArrayList<ArrayList<Integer>> result,
ArrayList<Integer> list, int[] num, int pos) {
result.add(new ArrayList<Integer>(list));
for (int i = pos; i < num.length; i++) {
list.add(num[i]);
subsetsHelper(result, list, num, i + 1);
list.remove(list.size() - 1);
}
}
In result.add(new ArrayList<Integer>(list))
why do I need to use new ArrayList<Integer>(list))
? I know simply using result.add(list)
would make the items in the result all the same, but I want to know the reason.
new ArrayList<Integer>(list)
This is called a copy constructor , " It is used to create a copy of an existing object of the same class. "
Without the copy constructor each call to result.add(list)
would add a reference to the same list repeatedly to result
. With the copy constructor a new list is created with the current values of list
. That way subsetHelper()
can repeatedly modify list
without also changing the lists already stored in result
.
Make sure you understand how Java passes around method parameters ; it's not complicated, but it is critical to being an effective Java programmer.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.