# 90. Subsets II 子集 II

@TOC

## # 题目描述

Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set).

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],
[]
]
``````

## # 解题方法

### # 递归

【LeetCode】78. Subsets 解题报告open in new window是一个不含重复元素的题。

Python代码如下：

``````class Solution(object):
def subsetsWithDup(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
res = []
nums.sort()
self.dfs(nums, 0, res, [])
return res

def dfs(self, nums, index, res, path):
if path not in res:
res.append(path)
for i in range(index, len(nums)):
if i > index and nums[i] == nums[i - 1]:
continue
self.dfs(nums, i + 1, res, path + [nums[i]])
``````

### # 回溯法

C++代码如下：

``````class Solution {
public:
vector<vector<int>> subsetsWithDup(vector<int>& nums) {
sort(nums.begin(), nums.end());
vector<vector<int>> res;
vector<int> path;
backtrack(res, path, nums, 0);
return res;
}
void backtrack(vector<vector<int>>& res, vector<int>& path, vector<int>& nums, int index) {
if (index > nums.size()) return;
res.push_back(path);
for (int i = index; i < nums.size(); ++i) {
if (i != index && nums[i] == nums[i - 1]) continue;
path.push_back(nums[i]);
backtrack(res, path, nums, i + 1);
path.pop_back();
}
}
};
``````

## # 日期

2018 年 4 月 2 日 —— 要开始准备ACM了 2018 年 12 月 21 日 —— 一周就要过去了 2019 年 9 月 25 日 —— 做梦都在秋招，这个秋天有毒