Subsets I

来源:互联网 发布:wish黄钻产品怎么优化 编辑:程序博客网 时间:2024/05/16 15:23

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

Analysis: DFS. Sort the array at the beginning. Each time, select the first element in the array, which is the smallest number in the array and the biggest number compared to all of the numbers in res, and insert itself and its combinations with all of the existing sets in res into res. 

public class Solution {    public void subsets(int[] S, ArrayList<ArrayList<Integer>> res) {        if(S.length == 0) {            res.add(new ArrayList<Integer>());      // empty set            return;        }                int size = res.size();        for(int i=0; i<size; i++) {            ArrayList<Integer> tem = new ArrayList<Integer>(res.get(i));            tem.add(S[0]);            res.add(tem);        }        int[] nextS = Arrays.copyOfRange(S, 1, S.length);        ArrayList<Integer> loc = new ArrayList<Integer>();        loc.add(S[0]);        res.add(loc);        subsets(nextS, res);    }        public ArrayList<ArrayList<Integer>> subsets(int[] S) {        ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();        Arrays.sort(S);        subsets(S, res);        return res;    }}


0 0
原创粉丝点击