生成一個集合的所有子集 Subset
阿新 • • 發佈:2019-02-17
典型的遞迴狀態生成問題。類似於全排列的生成問題。
問題一:無重複元素集合的子集。Given a set of distinct integers, S, return all possible subsets.
思路:藉助一個now陣列儲存臨時的子集。不斷切換狀態進行深層遞迴,在遞迴最深處儲存生成的子集。
class Solution { public: vector<vector<int> > subsets(vector<int> &S) { vector<vector<int> > result; if(S.empty()) return result; sort(S.begin(), S.end()); vector<int> now; fun(S, result, now, 0); return result; } void fun(const vector<int> &s, vector<vector<int> > &result, vector<int> &now, int n) { if(n == s.size()) { result.push_back(now); //遞迴最深處:所有元素都判定過取或不取 return; } else { fun(s, result, now, n+1); //不取 now.push_back(s[n]); fun(s, result, now, n+1); //取 now.pop_back(); //回溯前一定要恢復回原樣 } } };
問題二:有重複元素集合的子集。Given a collection of integers that might contain duplicates, S, return all possible subsets.
class Solution { public: vector<vector<int> > subsetsWithDup(vector<int> &S) { vector<vector<int> > result; vector<int> now; sort(S.begin(), S.end());//排序 set<vector<int> > s; backtrack(s, now, S, 0); set<vector<int> >::iterator it = s.begin(); for(;it != s.end();it++) result.push_back(*it); return result; } void backtrack(set<vector<int> > &result, vector<int> &now, vector<int> &S, int idx) { if(idx == S.size()) { result.insert(now);//set去重複 return; } backtrack(result, now, S, idx+1); now.push_back(S[idx]); backtrack(result, now, S, idx+1); now.pop_back(); } };