`
jgsj
  • 浏览: 961257 次
文章分类
社区版块
存档分类
最新评论

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,
IfS=[1,2,2], a solution is:

[
  [2],
  [1],
  [1,2,2],
  [2,2],
  [1,2],
  []
]

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


class Solution {
public:
	vector<vector<int> > subsetsWithDup(vector<int> &S) 
	{
		sort(S.begin(), S.end());
		vector<vector<int> > rs(1);
		vector<int> temp;
		set<vector<int> > 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<vector<int> > subsetsWithDup2(vector<int> &S) 
	{
		sort(S.begin(), S.end());
		vector<vector<int> > rs(1);
		vector<int> temp;
		set<vector<int> > 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<vector<int> > subsetsWithDup(vector<int> &S) 
	{
		sort(S.begin(), S.end());
		vector<vector<int> > rs(1);
		unordered_set<vector<int> > 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;
	}


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics