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 =
If S =
[1,2,3]
, a solution is:[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
Solution:
public class Solution { public List<List<Integer>> subsets(int[] S) { Arrays.sort(S); List<List<Integer>>solution = new ArrayList<List<Integer>>(); subsets(S, 0,new ArrayList<Integer>(), solution); return solution; } private void subsets(int[] S, int index, ArrayList<Integer> tempSolution, List<List<Integer>>solution) { if (index==S.length) { solution.add((List<Integer>)tempSolution.clone()); return; } // Not adding the element subsets(S, index+1, tempSolution, solution); tempSolution.add(S[index]); subsets(S, index+1, tempSolution, solution); tempSolution.remove(tempSolution.size()-1); } }
No comments :
Post a Comment