lintcode:子集 & 带重复元素的子集
地址:
http://lintcode.com/zh-cn/problem/subsets/
http://lintcode.com/zh-cn/problem/subsets-ii/
子集
其实就是一颗子集树
class Solution { public: vector<vector<int>> res; vector<int> judge; int len; /* * @param nums: A set of numbers * @return: A list of lists */ vector<vector<int>> subsets(vector<int> &nums) { // write your code here len = nums.size(); for(int i=0;i<len;i++){ judge.push_back(0); } backtrack(0,nums); return res; } void display(vector<int> &nums){ vector<int> cur; for(int i=0;i<len;i++){ if(judge[i]==1){ cur.push_back(nums[i]); } } res.push_back(cur); } void backtrack(int t,vector<int> &nums){ if(t >= len){ display(nums); return; } for(int i=0;i<=1;i++){ judge[t] = i; backtrack(t+1,nums); } } };
带重复元素的子集
筛选一下分支,排序数组,然后相同的元素只能出现1,...,0...或者全1、全0的形式,也就是不能有101这样的情况,
class Solution { public: vector<vector<int>> res; vector<int> judge; int len; /* * @param nums: A set of numbers. * @return: A list of lists. All valid subsets. */ vector<vector<int>> subsetsWithDup(vector<int> &nums) { // write your code here len = nums.size(); sort(nums.begin(),nums.end()); for(int i=0;i<len;i++){ judge.push_back(0); } backtrack(0,nums); return res; } void display(vector<int> &nums){ vector<int> cur; for(int i=0;i<len;i++){ if(judge[i]==1){ cur.push_back(nums[i]); } } res.push_back(cur); } bool isOk(int t,vector<int> &nums){ int count=1; for(int i=0;i<t;i++){ if(nums[i]==nums[i+1]){ if(judge[i]==0){ count = 0; } else { count = 1; } if(!count && judge[i+1] ){ return false; } } else { count=1; } } return true; } void backtrack(int t,vector<int> &nums){ if(t >= len){ display(nums); return; } for(int i=0;i<=1;i++){ judge[t] = i; if(isOk(t,nums)){ backtrack(t+1,nums); } } } };