78. Subsets
Given a set of distinct integers, nums, return all possible subsets (the power set).
Note: The solution set must not contain duplicate subsets.
Example:
Input: nums = [1,2,3] Output: [ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ]
C++:
1 class Solution { 2 public: 3 void process(vector<int>& nums, vector<int>& path, int index, vector<vector<int> >&result){ 4 //终止条件,路径保存 5 if (index == nums.size()){ 6 result.push_back(path); 7 return; 8 } 9 process(nums, path, index+1, result); 10 path.push_back(nums[index]); 11 process(nums, path, index + 1, result); 12 //恢复上一级的path 13 path.pop_back(); 14 } 15 16 vector<vector<int>> subsets(vector<int>& nums) { 17 sort(nums.begin(), nums.end()); 18 vector<vector<int> > result; 19 vector<int> path; 20 process(nums, path, 0, result); 21 return result; 22 } 23 };