标签:
标题: | Subsets |
通过率: | 28.2% |
难度: | 中等 |
Given a set of distinct integers, S, return all possible subsets.
Note:
For example,
If S = [1,2,3]
, a solution is:
[ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ]
本题思路就是找出所有子集,具体看代码:
1 public class Solution { 2 3 ArrayList<ArrayList<Integer>> ans = new ArrayList<ArrayList<Integer>>(); 4 5 public ArrayList<ArrayList<Integer>> subsets(int[] S) { 6 Arrays.sort(S); 7 // length of subsets: from 0 to S.length 8 for (int i = 0; i <= S.length; i++) { 9 backTracking(new ArrayList<Integer>(), 0, i,S); 10 } 11 return ans; 12 } 13 14 public void backTracking(ArrayList<Integer> list, int from, int tar,int[] S) { 15 if (list.size() == tar) { 16 ArrayList<Integer> res = new ArrayList<Integer>(list); 17 ans.add(res); 18 } else { 19 for (int i = from; i < S.length; i++) { 20 list.add(S[i]); 21 backTracking(list, i + 1, tar,S); 22 list.remove(list.size()-1); 23 } 24 } 25 } 26 }
标签:
原文地址:http://www.cnblogs.com/pkuYang/p/4341947.html