标签:
Given a set of distinct integers, nums, return all possible subsets.
Note:
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 { public: void getSubsets(vector<vector<int>> &res, vector<int> nums, vector<int> v, int n, int m, int k, int idx) { if(k == m) { res.push_back(v); v.clear(); return; } for(int i = idx; i < n; i++) { v.push_back(nums[i]); getSubsets(res, nums, v, n, m, k+1, i+1); v.pop_back(); } } vector<vector<int>> subsets(vector<int>& nums) { vector<vector<int>> res; vector<int> v; res.push_back(v); int n = nums.size(), i; if(0 == n) return res; sort(nums.begin(), nums.end()); for(i = 1; i <= n; i++) { getSubsets(res, nums, v, n, i, 0, 0); } return res; } };
2.非递归
class Solution { public: void getSubsets(vector<vector<int>> &res, vector<int> nums, int n, int m) { vector<int> d; int i, j; for(i = 0; i < n; i++) { d.push_back((i < m) ? 1 : 0); } while(1) { vector<int> v; for(i = 0; i < n; i++) { if(d[i]) v.push_back(nums[i]); } res.push_back(v); //find [1, 0] pattern bool found = false; int ones = 0; for(i = 0; i < n-1; i++) { if(1 == d[i] && 0 == d[i+1]) { d[i] = 0; d[i+1] = 1; found = true; for(j = 0; j < i; j++) { d[j] = (ones > 0) ? 1 : 0; ones--; } break; } if(1 == d[i]) ones++; } if(!found) break; } } vector<vector<int>> subsets(vector<int>& nums) { vector<vector<int>> res; vector<int> v; res.push_back(v); int n = nums.size(), i; if(0 == n) return res; sort(nums.begin(), nums.end()); for(i = 1; i <= n; i++) { getSubsets(res, nums, n, i); } return res; } };
标签:
原文地址:http://www.cnblogs.com/argenbarbie/p/5323397.html