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],

  []

]

有了前面那道小难的Combinations做铺垫,再来写这道题的recursion就要容易很多很多了。只是把上道题的k变成可变的,取值范围从0到S.length。加一层循环就好了。可以说,找subset的核心,其实还是在找n个数中k个数组成的combination sets。

 1 import java.util.*;

 2 

 3 public class Solution {

 4     public ArrayList<ArrayList<Integer>> subsets(int[] S) {

 5         java.util.Arrays.sort(S);

 6         ArrayList<Integer> set = new ArrayList<Integer>();

 7         ArrayList<ArrayList<Integer>> sets = new ArrayList<ArrayList<Integer>>();

 8         

 9         for (int k = 0; k <= S.length; i++) {

10             helper(set, sets, S, k, 0);

11         }

12         return sets;

13     }

14     

15     public void helper(ArrayList<Integer> set, ArrayList<ArrayList<Integer>> sets, int[] S, int k, int starter){

16         if (set.size() == k) {

17             sets.add(new ArrayList<Integer>(set));

18             return;

19         }

20         for (int j = starter; j <= S.length - 1; j++) {

21             set.add(S[j]);

22             helper(set, sets, S, k, j+1);

23             set.remove(set.size() - 1);

24         }

25     }

26 }

 

你可能感兴趣的:(LeetCode)