您的位置:首页 > 其它

[LeetCode]Subsets II

2013-06-01 09:46 127 查看
class Solution {
//because Elements in a subset must be in non-descending order.
//so if we sort the vector first.
//If we choose an elem[i] into subset, then we should choose elem[j](i<j<n) into the subset,
//repeat this until there is no element left any more.
//But note: in the same level we can not choose multiple same elements as the new heads of the next subset.

void DFS(vector<int>& S, int curPos, vector<int>& oneSubset, vector<vector<int>>& allSubset)
{
allSubset.push_back(oneSubset);
for (int i = curPos; i < S.size(); ++i)
{
if(i != curPos && S[i] == S[i-1]) continue;

oneSubset.push_back(S[i]);
DFS(S, i+1, oneSubset, allSubset);
oneSubset.pop_back();
}

}
public:
vector<vector<int> > subsetsWithDup(vector<int> &S) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
sort(S.begin(), S.end());
vector<int> oneSubset;
vector<vector<int>> allSubset;
DFS(S, 0, oneSubset, allSubset);
return allSubset;
}
};

second time

class Solution {
public:
void subsetUtil(vector<int>& S, vector<bool>& used, int curIdx, vector<int>& curPath, vector<vector<int> >& allPath)
{
if(curIdx == S.size())
{
allPath.push_back(curPath);
return ;
}

subsetUtil(S, used, curIdx+1, curPath, allPath);
if(curIdx >= 1 && S[curIdx] == S[curIdx-1] && used[curIdx-1] == false) return;
used[curIdx] = true;
curPath.push_back(S[curIdx]);
subsetUtil(S, used, curIdx+1, curPath, allPath);
curPath.pop_back();
used[curIdx] = false;
}
vector<vector<int> > subsetsWithDup(vector<int> &S) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
sort(S.begin(), S.end());
vector<bool> used(S.size(), false);
vector<vector<int> > allPath;
vector<int> curPath;
subsetUtil(S, used, 0, curPath, allPath);
return allPath;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: