[LeetCode] Subsets
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],
[]
]
Discuss
java code :
public class Solution { public ArrayList<ArrayList<Integer>> subsets(int[] S) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>(); res.add(new ArrayList<Integer>()); if(S.length ==0) return res; Arrays.sort(S); ArrayList<Integer> tmp = new ArrayList<Integer>(); for(int i = 1; i <= S.length; i++) { tmp.clear(); recursion(res,tmp,i,S,0); } return res; } public void recursion(ArrayList<ArrayList<Integer>> res, ArrayList<Integer> tmp, int k, int[] S, int dp) { if(k == tmp.size()) { res.add(new ArrayList<Integer>(tmp)); return ; } for(int i = dp; i < S.length; i++) { tmp.add(S[i]); recursion(res,tmp,k,S,i+1); tmp.remove(tmp.size() - 1); } } }
补充:综合编程 , 其他综合 ,