脑子有点混,少数次过
1 class Solution { 2 public: 3 void dfs(int cur, int n, vector<vector<int>> &ret, vector<int> &tmp, vector<int> S) { 4 if (cur == n) { 5 ret.push_back(tmp); 6 return; 7 } 8 dfs(cur+1, n, ret, tmp, S); 9 tmp.push_back(S[cur]); 10 dfs(cur+1, n, ret, tmp, S); 11 tmp.pop_back(); 12 } 13 vector<vector<int> > subsets(vector<int> &S) { 14 // Start typing your C/C++ solution below 15 // DO NOT write int main() function 16 sort(S.begin(), S.end()); 17 vector<vector<int>> ret; 18 if (!S.size()) return ret; 19 vector<int> tmp; 20 dfs(0, S.size(), ret, tmp, S); 21 return ret; 22 } 23 };
C#
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public class Solution { 2 public List<List<int>> Subsets(int[] nums) { 3 Array.Sort(nums); 4 List<List<int>> ans = new List<List<int>>(); 5 if (nums.Length == 0) return ans; 6 List<int> tmp = new List<int>(); 7 dfs(0, nums.Length, ref ans, ref tmp, nums); 8 return ans; 9 } 10 public void dfs(int cur, int n, ref List<List<int>> ans, ref List<int> tmp, int[] nums) { 11 if (cur == n) { 12 ans.Add(new List<int>(tmp.ToArray())); 13 return; 14 } 15 dfs(cur+1, n, ref ans, ref tmp, nums); 16 tmp.Add(nums[cur]); 17 dfs(cur+1, n, ref ans, ref tmp, nums); 18 tmp.RemoveAt(tmp.Count - 1); 19 } 20 }