Subsets II解題報告

Description:

Given a list of numbers that may has duplicate numbers, return all possible subsets

Notice:

Each element in a subset must be in non-descending order.
The ordering between two subsets is free.
The solution set must not contain duplicate subsets.

Example:

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

Link:

http://www.lintcode.com/en/problem/subsets-ii/#

解題方法:

同樣是DFS, 只是需要多一個去重步驟。

Tips:

去重代碼:
if(i != start && S[i] == S[i-1]) continue;
當循環時碰到與上一個相同的元素直接continue

完整代碼:

vector<vector<int> > result; vector<vector<int> > subsetsWithDup(const vector<int> &S) { if(S.size() == 0) { result.push_back({}); return result; } vector<int> source = S; sort(source.begin(), source.end()); vector<int> temp; helper(source, temp, 0); return result; } void helper(const vector<int> &S, vector<int> &temp, int start) { result.push_back(temp); for(int i = start; i < S.size(); i++) { if(i != start && S[i] == S[i-1]) continue; temp.push_back(S[i]); helper(S, temp, i+1); temp.pop_back(); } return; }

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容