LeetCode OJ: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:
求所有的子集合的问题,只不过这里的子集合里面的数字不会发生重复的,实际上比另一个会重复的还要简单一点,也是用dfs就可以解决,我还是喜欢将传递的变量生命成为private,这样方便一点,避免出现很长的参数列表:
1 class Solution { 2 public: 3 vector<vector<int>> subsets(vector<int>& nums) { 4 sort(nums.begin(), nums.end()); 5 rawVec = nums; 6 tmp.clear(); 7 ret.clear(); 8 dfs(0); 9 return ret; 10 } 11 12 void dfs(int start) 13 { 14 ret.push_back(tmp); 15 if(start >= raw.size()) return; 16 if(start < rawVec.size()){ 17 for(int i = start + 1; i < rawVec.size(); ++i){ 18 tmp.push_back(i); 19 dfs(i); 20 tmp.pop_back(); 21 } 22 } 23 } 24 private: 25 vector<vector<int>> ret; 26 vector<int> tmp; 27 vector<int> rawVec; 28 };
java版本的代码如下所示,基本上去除了所有的全局变量,和Subsets II的java代码基本上是相同的:
1 public class Solution { 2 public List<List<Integer>> subsets(int[] nums) { 3 Arrays.sort(nums); 4 List<List<Integer>> ret = new ArrayList<List<Integer>>(); 5 List<Integer>tmp = new ArrayList<Integer>(); 6 dfs(ret, tmp, 0, nums, nums.length); 7 return ret; 8 } 9 10 public void dfs(List<List<Integer>> ret, List<Integer> tmp, int start, int [] nums, int limit){ 11 if(start > limit) 12 return; 13 else if(start == limit){ 14 ret.add(new ArrayList(tmp)); 15 }else{ 16 ret.add(new ArrayList(tmp)); 17 for(int i = start; i < limit; ++i){ 18 tmp.add(nums[i]); 19 dfs(ret, tmp, i+1, nums, limit); 20 tmp.remove((Integer)nums[i]); 21 } 22 } 23 } 24 }