Leetcode: Subsets

来源:互联网 发布:ubuntu 任务栏 不显示 编辑:程序博客网 时间:2024/05/11 17:44

Problem:

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


Solution: 

DFS.

Analysis:  Reference from http://www.cnblogs.com/springfor/p/3879830.html

 "The mathematical definition of a set ensures the uniqueness of its elements. For a set of cardinality n, the number of its subsets is 2^n. A DFS will traverse every one of them. During each recursion, you can either choose this element or not, resulting in two recursive path."


code:

public class Solution {    ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();    public ArrayList<ArrayList<Integer>> subsets(int[] S) {        if (S == null || S.length == 0) {            ArrayList<Integer> tmp = new ArrayList<Integer>();            result.add(tmp);            return result;        }        Arrays.sort(S);        dfs(0,0,S.length,new ArrayList<Integer>(), S);        result.add(new ArrayList<Integer>());        return result;                    }    public void dfs(int start, int level, int length, ArrayList<Integer> list, int[] S) {        if (start == length) return;        if (level >= length) {            return;        }        for (int i = start; i < length; i++) {            list.add(S[i]);            ArrayList<Integer> tmp = new ArrayList<Integer>(list);            result.add(tmp);            dfs(i + 1, level + 1, length, list, S);            list.remove(list.size() - 1);        }    }}


0 0
原创粉丝点击