Leetcode 78. Subsets & 90. Subsets II
2017-08-21 09:35
453 查看
题目来源: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; } }
相关文章推荐
- leetcode解题之 77. Combinations&78. Subsets&90. Subsets II java 版(求所有子集)
- [LeetCode] Subsets I (78) & II (90) 解题思路,即全组合算法
- leetcode题解-78. Subsets && 90. Subsets II
- leetcode 491. Increasing Subsequences & lc 78. Subsets
- 78. Subsets & 90. Subsets II
- <LeetCode OJ> 78 / 90 Subsets (I / II)
- <LeetCode OJ> 78. Subsets
- [leetcode 78 & 90, Medium] Subsets I and II
- LeetCode - 78 - Subsets(求数组全部子集)
- LeetCode78 SubSets
- LeetCode Subsets && Subsets II
- LeetCode-Subsets & Subsets II
- LeetCode 78 --- Subsets
- LeetCode 78: Subsets
- [Leetcode]#78 Subsets
- LeetCode78 Subsets
- [LeetCode] 78. Subsets
- leetcode || 78、Subsets
- LeetCode(78) Subsets
- Leetcode 78. Subsets