首页 > 代码库 > [leetcode] Subsets

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

https://oj.leetcode.com/problems/subsets/

 

思路:递归构造,每一层递归都选择填或者不填s[cur]的操作。

import java.util.ArrayList;import java.util.Arrays;public class Solution {    public ArrayList<ArrayList<Integer>> subsets(int[] S) {        ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();        ArrayList<Integer> tmp = new ArrayList<Integer>();        Arrays.sort(S);        subsetsHelper(res, tmp, S, 0);        return res;    }    private void subsetsHelper(ArrayList<ArrayList<Integer>> res, ArrayList<Integer> tmp, int[] s, int cur) {        if (cur == s.length) {            res.add(new ArrayList<Integer>(tmp));            return;        }        // not fill        subsetsHelper(res, tmp, s, cur + 1);        // fill        tmp.add(s[cur]);        subsetsHelper(res, tmp, s, cur + 1);        tmp.remove(tmp.size() - 1);    }    public static void main(String[] args) {        System.out.println(new Solution().subsets(new int[] { 4, 1, 0 }));    }}
View Code