【LeetCode】90. Subsets II

题目:

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.

Example:

Input: [1,2,2]
Output:
[
  [2],
  [1],
  [1,2,2],
  [2,2],
  [1,2],
  []
]

 

描述:

给出一个包含重复数字的数组,要求输出该数组的所有子集

 

分析:

简单的搜索题,没有什么难度

 

代码:

class Solution {
public:
	vector<vector<int>> subsetsWithDup(vector<int>& nums) {
		sort(nums.begin(), nums.end());
		set<vector<int>> result_set;
		
		for (int i = 0; i <= nums.size(); ++ i) {
			vector<int> current;
			dfs(nums, 0, i, current, result_set);
		}
		vector<vector<int>> result;
        result.assign(result_set.begin(), result_set.end());
		return result;
	}
	void dfs(const vector<int>& nums, int current_index, int count, vector<int> &current, set<vector<int>>& result) {
		if (!count) {
			result.insert(current);
			return;
		}
		if (current_index >= nums.size()) {
			return;
		}
		
		dfs(nums, current_index + 1, count, current, result);
		
		current.push_back(nums[current_index]);
		dfs(nums, current_index + 1, count - 1, current, result);
		current.pop_back();
	}
};

 

 

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页