Given a set of distinct integers, S, 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 S =
[1,2,3]
, a solution is:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
==================
Analysis:
First of all, I don't think this problem is easy (many blogs mentioned that it is a basic recursion problem, maybe it is a sample in the text book, but it's not my case). This problem can be simplified to given an array, then find out all the subsets in certain length. For example, given array [1,2,3,4,5], find out all the subset in the length of 3 ([1,2,3] [1,2,4] [1,2,5] [1,3,4] [1,3,5] ...). After we have this solution, we can use an iteration to do subset length=0,1,2,3,4,5 to solve our "Subsets" problem.
Regarding to the simplified problem, we can use recursive approach, process of which as below:
1. Choose the 1st number from given array.
2. Use recursive call to choose length-1 numbers from array excluding the numbers that have been chosen.
Exit of the recursive call: when length of the constructing array reach the required subset length, then add it to the result set and return.
public class Solution {
public ArrayList<ArrayList<Integer>> subsets(int[] S) {
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
// for test case
Arrays.sort(S);
// length a subset
for(int i=0; i<=S.length; i++){
ArrayList<Integer> subResult = new ArrayList<Integer>();
helper(S, result, subResult, i, 0);
}
return result;
}
public void helper(int[] S, ArrayList<ArrayList<Integer>> result, ArrayList<Integer> subResult, int length, int elementNum){
if(subResult.size() == length){
result.add(new ArrayList<Integer>(subResult));
return;
}
for(int i=elementNum; i<S.length; i++){ // for each element in S
subResult.add(S[i]); // choose the 1st number for subset
helper(S, result, subResult, length, i+1); // choose the remaining numbers for subset
subResult.remove(subResult.size()-1); // remove the chosen 1st number, and rechoose it in the next iteration
}
}
}