【Leetcode】Subsets
来源:互联网 发布:冰箱哪个牌子好 知乎 编辑:程序博客网 时间:2024/06/17 05:49
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:
[ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], []]——————————————————————————————————————————————————————————
This one is actually very trivial and requires careful thinking while programming it.
The basic idea should be: one for-loop counting the number of elements needed for this-round permutation. And within the permutation, lets say our permutation function called permu(array, i). each round the permu(array,i) is supposed to be permu(array,i)+for-loop(0~array.length-1). And certainly, the basic case is permu(array, 1) which represents [array[0],array[1],...array[-1]].
However, there are several tricky points that you need to pay attention to.
Function permu needs the "starting point" because the thing is *Count ONLY RECORDS HOW MANY NUMBER YOU WANNA PERMUTE* while *Start REPRESENT INSIDE THE FUNCTION PERMUTATION WHICH NUMBER YOU SHOULD BE "THE PRE-ADDING ONE"*. For Example, array = {1,2,3,4,5}, this round you are supposed to execute permu(count=4, start=0, array). Inside the function, for(start ~ array.length){s_list.add(array[start]) then do list.add(permu(count=4-1, start=1,array))}. Of course, you must hope List<List<>> and List<integer> goes with the recursion together.
public class Solution { public List<List<Integer>> subsets(int[] nums) { List<List<Integer>> list= new ArrayList<List<Integer>>();if(nums==null || nums.length==0)return list;Arrays.sort(nums); for(int i=0;i<=nums.length;i++){ permutation(i,0,nums, new ArrayList<Integer>(), list); } return list; } private void permutation(int count, int start, int[] nums, List<Integer> tmp, List<List<Integer>> res){if (tmp.size() == count) { res.add(tmp); return; } for (int i = start; i < nums.length; i++) { List<Integer> newTemp = new ArrayList<Integer>(tmp); // new the arraylist with last round pre-adding element newTemp.add(nums[i]); permutation(count, i + 1, nums, newTemp, res); }}}
Voila!
- 【LeetCode】 Subsets Subsets II
- 【LeetCode】Subsets & Subsets II
- LeetCode Subsets && Subsets II
- LeetCode Subsets && Subsets II
- LeetCode-Subsets & Subsets II
- LeetCode: Subsets
- LeetCode Subsets
- [Leetcode] Subsets
- LeetCode : Subsets
- [LeetCode] Subsets
- Leetcode: Subsets
- Leetcode: Subsets ||
- [leetcode] subsets
- Leetcode - Subsets
- [LeetCode]Subsets
- LeetCode-Subsets
- LeetCode - Subsets
- LeetCode | Subsets
- 在 Windows 平台上运行 FreeRTOS 示例程序
- Codeforce 题目621C Wet Shark and Flowers(期望)
- 一个简单的DBHelper
- openCV学习记录:滤镜:碎片&暗调
- 【Leetcode】Maximum Size Subarray Sum Equals k
- 【Leetcode】Subsets
- 蓝桥杯 算法训练 2的次幂表示(构造)
- windows命令行长度的限制
- windows server上配置 apache + php + MySQL + wordpress
- git之安装配置篇
- ubuntu下git安装使用
- ios9 第三方SDK无法回调问题
- 【Leetcode】Reverse LinkedList
- CodeBlock速配wxWidgets