/*
90. Subsets II
My Submissions
Question
Editorial Solution
Total Accepted: **69575** Total Submissions: **224792** Difficulty: **Medium**
Given a collection of integers that might contain duplicates, ***nums***, return all possible subsets.
**Note:** The solution set must not contain duplicate subsets.
For example,
If ***nums*** = [1,2,2], a solution is:
[
[2],
[1],
[1,2,2],
[2,2],
[1,2],
[]
]
Hide Company Tags Facebook
Hide Tags Array Backtracking
*/
public class Solution {
public List<List<Integer>> subsetsWithDup(int[] nums) {
//https://leetcode.com/discuss/54544/very-simple-and-fast-java-solution
/*
The Basic idea is: use "while (i < n.length && n[i] == n[i - 1]) {i++;}" to avoid the duplicate. For example, the input is 2 2 2 3 4. Consider the helper function. The process is:
each.add(n[i]); --> add first 2 (index 0)
helper(res, new ArrayList<>(each), i + 1, n); --> go to recursion part, list each is <2 (index 0)>
while (i < n.length && n[i] == n[i - 1]) {i++;} --> after this, i == 3, add the element as in subset I
*/
Arrays.sort(nums);
List<List<Integer>> res = new ArrayList<>();
List<Integer> cur = new ArrayList<>();
helper(res, cur, 0, nums);
return res;
}
public void helper(List<List<Integer>> res, List<Integer> cur, int pos, int[] n) {
if (pos <= n.length) {
res.add(cur);
}
int i = pos;
while (i < n.length) {
cur.add(n[i]);
helper(res, new ArrayList<>(cur), i+1, n);
cur.remove(cur.size() - 1);
i++;
while( i < n.length && n[i] == n[i-1]) {
i++;
}
}
return;
}
}
90. Subsets II
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- Given a collection of integers that might contain duplica...