2013.12.26 15:19
Given a set of distinct integers, 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,
If S = [1,2,3]
, a solution is:
[ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ]
Solution:
The mathematical definition of a set ensures the uniqueness of its elements. For a set of cardinality n, the number of its subsets is 2^n. A DFS will traverse every one of them. During each recursion, you can either choose this element or not, resulting in two recursive path.
Time complexity is O(2^n), where n is the cardinality of the set. Space complexity is O(n).
Accepted code:
1 // 2CE, 1OLE, 1RE, 4WA, 1AC, so difficult... 2 class Solution { 3 public: 4 vector<vector<int> > subsets(vector<int> &S) { 5 // IMPORTANT: Please reset any member data you declared, as 6 // the same Solution instance will be reused for each test case. 7 int i, n; 8 9 n = result.size(); 10 for(i = 0; i < n; ++i){ 11 result[i].clear(); 12 } 13 result.clear(); 14 // 1WA here, S is not sorted, thus need sorting to ensure that the result is sorted 15 sort(S.begin(), S.end()); 16 arr.clear(); 17 n = S.size(); 18 // 1CE here, ; is missing after dfs 19 dfs(0, n, S); 20 21 return result; 22 } 23 private: 24 vector<vector<int>> result; 25 vector<int> arr; 26 27 // 1CE here, S is not declared in this scope 28 void dfs(int idx, int n, vector<int> &S) { 29 // 1RE here, didn't check n, out of range 30 // 1WA here, only push result when idx == n, or else would have redundant results. 31 if(idx == n){ 32 result.push_back(arr); 33 return; 34 } 35 36 // 1OLE here, for(i = idx; i < n; ++i) structure is wrong, need no for 37 dfs(idx + 1, n, S); 38 arr.push_back(S[idx]); 39 dfs(idx + 1, n, S); 40 arr.pop_back(); 41 } 42 };