leetcode5:subsets问题
问题描述:
Given a set of distinct integers, nums, 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 nums = [1,2,3]
, a solution is:
[ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ]
方法一:迭代
1 class Solution { 2 public: 3 vector<vector<int>> subsets(vector<int>& nums) { 4 sort(nums.begin(),nums.end()); 5 vector<int> v; 6 vector<vector<int>> res; 7 res.push_back(v); 8 for(int i=0;i<nums.size();i++) 9 { 10 for(int j=res.size()-1;j>=0;j--) 11 { 12 v.assign(res[j].begin(),res[j].end()); 13 v.push_back(nums[i]); 14 res.push_back(v); 15 } 16 } 17 return res; 18 } 19 };
方法二:递归
1 class Solution { 2 public: 3 vector<vector<int>> subsets(vector<int>& nums) { 4 sort(nums.begin(),nums.end()); 5 vector<vector<int>> res; 6 res.reserve(pow(2,nums.size())); 7 vector<int> v; 8 subset(res,nums,0,v); 9 return res; 10 } 11 private: 12 void subset(vector<vector<int>>& res,vector<int>& s,int start,vector<int>& v) 13 { 14 if(start == s.size()) 15 { 16 res.push_back(v); 17 return; 18 } 19 subset(res,s,start+1,v); 20 v.push_back(s[start]); 21 subset(res,s,start+1,v); 22 v.pop_back(); 23 } 24 };