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!