Subsets II

 

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

Note:
code

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

 

有圖爲證:ip

class Solution {
public:
    void subReII(vector<vector<int> >& re, vector<int> &s,int j)
	{
		if(s.size() <= j)
			return;
		int size_ = re.size();
		int k = j + 1;
		//get the 重複區間,k是下個不重複的位置。
		while(k < s.size() && s[k] == s[k - 1]) k++;
		for(int i = 0; i < size_; ++i)
		{
			int cur = j;
			vector<int> copy(re[i]);
			//將重複的元素從 1 個到全部依次加入進去。
			while(cur < k)
			{
				copy.push_back(s[j]);
			    re.push_back(copy);
				++cur;
			}
		}
		//skip the 重複區間,到下一個不是重複的位置,遞歸。
		subReII(re, s, k);
	}
	vector<vector<int> > subsetsWithDup(vector<int> &S) {
		vector<vector<int> > re;
		vector<int> sol;
		sort(S.begin(),S.end());
		re.push_back(sol);
		subReII(re, S, 0);
		return re;
	}
};
相關文章
相關標籤/搜索