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

禁止重复,就使用set,map等容器,就可以很简单解决了。


class Solution {
public:
	vector > subsetsWithDup(vector &S) 
	{
		sort(S.begin(), S.end());
		vector > rs(1);
		vector temp;
		set > us;
		us.insert(temp);

		for (int i = 0; i < S.size(); i++)
		{
			for (int j = rs.size()-1; j>=0; j--)
			{
				temp = rs[j];
				temp.push_back(S[i]);
				rs.push_back(temp);
				us.insert(temp);
			}
		}
		rs.clear();
		rs.assign(us.begin(), us.end());
		return rs;
	}

	vector > subsetsWithDup2(vector &S) 
	{
		sort(S.begin(), S.end());
		vector > rs(1);
		vector temp;
		set > us;
		us.insert(temp);

		for (int i = 0; i < S.size(); i++)
		{
			for (int j = rs.size()-1; j>=0; j--)
			{
				temp = rs[j];
				temp.push_back(S[i]);
				rs.push_back(temp);
				us.insert(temp);
			}
			rs.assign(us.begin(),us.end());
		}
		return rs;
	}
};


//2014-2-14 update
	vector > subsetsWithDup(vector &S) 
	{
		sort(S.begin(), S.end());
		vector > rs(1);
		unordered_set > sv(rs.begin(), rs.end());
		for (int i = 0; i < S.size(); i++)
		{
			for (int j = rs.size() - 1; j >= 0 ; j--)
			{
				rs.push_back(rs[j]);
				rs.back().push_back(S[i]);
				sv.insert(rs.back());
			}
			rs.assign(sv.begin(), sv.end());
		}
		return rs;
	}


你可能感兴趣的:(Algorithm算法,算法和数据结构C++实现)