/*
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
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
相关阅读更多精彩内容
- Given a collection of integers that might contain duplica...