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], [] ]
C++:
无重复子集问题:Subsets
class Solution { public: void dfs(const vector<int> &S, vector<int>::iterator start, vector<int> &path, vector<vector<int> > &result) { result.push_back(path); for (auto i = start; i < S.end(); i++) { //以每一个元素开头做一次深搜 //if (i != start && *i == *(i - 1)) continue; //同样起到跳过重复元素作用 path.push_back(*i); dfs(S, i + 1, path, result); path.pop_back(); while (i!=S.end()-1 && *i == *(i + 1)) //回溯时跳过重复的元素 i++; } } vector<vector<int> > subsetsWithDup(vector<int> &S) { sort(S.begin(), S.end()); vector<vector<int> > result; vector<int> path; dfs(S, S.begin(), path, result); return result; } };