题目来源:leetcode
Given a set of
distinct integers,
nums, return all possible subsets.
Note: The solution set must not contain duplicate subsets.
For example,
If nums = [1,2,3]
, a solution is:
思路:http://www.cnblogs.com/felixfang/p/3775712.html
代码:
class Solution {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> ls=new ArrayList<List<Integer>>();//用来存放结果
if (nums.length==0)
return ls;
ls.add(new ArrayList<Integer>());//初始加入空
for (int j=0;j<nums.length;j++){
List<List<Integer>> temp=new ArrayList<>();//存放数组每增加一个元素,结果需要增加的元素
//增加的元素为;上次所有结果集中,每个list中加入当前数组的数,别忘了在加上结果集中原有的元素
for(List<Integer> a:ls){
List<Integer> merge=new ArrayList<Integer>(a);
merge.add(nums[j]);
temp.add(merge);
}
ls.addAll(temp);
}
return ls;
}
}
II
Given a collection of integers that might contain duplicates,
nums, return all possible subsets.
Note: The solution set must not contain duplicate subsets.
For example,
If nums = [1,2,2]
, a solution is:
思路:存在重复元素,思路同上,注意先对数组进行排序
class Solution {
public List<List<Integer>> subsetsWithDup(int[] nums) {
List<List<Integer>> res=new ArrayList<>();
int index=1;
//List<Integer> lin=new ArrayList<>();
if(nums.length<=0)
return res;
res.add(new ArrayList<Integer>());
Arrays.sort(nums);//先进行排序
List<Integer> temp1=new ArrayList<>();
temp1.add(nums[0]);
res.add(temp1);
if(nums.length==1){
return res;
}
for(int i=1;i<nums.length;i++){
List<List<Integer>> temp=new ArrayList<>();//存放本次增加的元素
if(nums[i]!=nums[i-1])
{ index=res.size();
for(List<Integer> ls:res){
List<Integer> a=new ArrayList<>(ls);
a.add(nums[i]);
temp.add(a);
}
}
else{
for(int j=index;j<res.size();j++){
List<Integer> a=new ArrayList<>(res.get(j));
a.add(nums[i]);
temp.add(a);
}
index=res.size();
}
res.addAll(temp);
}
return res;
}
}