【发布时间】:2023-03-04 04:12:01
【问题描述】:
http://oj.leetcode.com/problems/subsets-ii/
给定一个可能包含重复的整数集合 S,返回所有可能的子集。
注意:
* Elements in a subset must be in non-descending order.
* The solution set must not contain duplicate subsets.
例如, 如果 S = [1,2,2],则解为:
[
[2],
[1],
[1,2,2],
[2,2],
[1,2],
[]
]
答案是:
public class Solution {
public ArrayList<ArrayList<Integer>> subsetsWithDup(int[] num) {
ArrayList<ArrayList<Integer>> ans = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> tmp = new ArrayList<Integer>();
Arrays.sort(num);
sub(num, 0, tmp, ans);
return ans;
}
public void sub(int[] num, int k, ArrayList<Integer> tmp, ArrayList<ArrayList<Integer>> ans) {
ArrayList<Integer> arr = new ArrayList<Integer>(tmp);
ans.add(arr);
for (int i = k; i < num.length; i++) {
if (i != k && num[i] == num[i-1]) continue;
tmp.add(num[i]);
sub(num, i+1, tmp, ans);
tmp.remove(tmp.size()-1);
}
}
}
不知道为什么
ArrayList<Integer> arr = new ArrayList<Integer>(tmp);
ans.add(arr);
但不是直接:
ans.add(tmp);
【问题讨论】:
-
您是否尝试过您认为应该做的事情并检查会发生什么?