LeetCode Subsets II

Subsets II

Given a collection of integers that might contain duplicates, S, return all possible subsets.

Note:

  • Elements in a subset must be in non-descending order.
  • The solution set must not contain duplicate subsets.

For example,
If S = [1,2,2], a solution is:

[
  [2],
  [1],
  [1,2,2],
  [2,2],
  [1,2],
  []
]
class Solution {
public:
    vector<vector<int> > subsetsWithDup(vector<int> &S) {
        vector<vector<int> > ret;
    	vector<int> copyS(S);
		sort(copyS.begin(), copyS.end());
		vector<int> digits;
		vector<int> counts;
		for(int i = 0; i < copyS.size(); ++i)
		{
			if(digits.empty() || digits.back() != copyS.at(i))
			{
				digits.push_back(copyS.at(i));
				counts.push_back(0);
			}
			++counts.back();
		}
		vector<int> result(counts.size());
		dfs(ret, result, digits, counts, 0);
		return ret;
    }

	void dfs(vector<vector<int> >& ret, vector<int>& result, vector<int>& digits, vector<int>& counts, int cur)
	{
		if(counts.size() == cur)
		{
			ret.push_back(vector<int>());
			for(int i = 0; i < result.size(); ++i)
				for(int j = 0; j < result[i]; ++j)
					ret.back().push_back(digits[i]);
		}
		else
		{
			for(int i = 0; i <= counts[cur]; ++i)
			{
				result[cur] = i;
				dfs(ret, result, digits, counts, cur+1);
			}

		}
	}
};

你可能感兴趣的:(LeetCode Subsets II)