Subsets

https://leetcode.com/problems/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],

  []

]

解题思路:

典型的深度遍历,所有的子集其实就是capacity为0-n的所有组合可能。而且这里的排序、去重问题,前面都遇到过。

 

public class Solution {

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

        List<List<Integer>> result = new LinkedList<List<Integer>>();

        List<Integer> current = new LinkedList<Integer>();

        Arrays.sort(S);

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

            dfs(result, current, S, i + 1, 0);

        }

        result.add(new LinkedList<Integer>());

        return result;

    }

    

    public void dfs(List<List<Integer>> result, List<Integer> current, int[] S, int capacity, int step){

        if(step == capacity){

            result.add(new LinkedList(current));

            return;

        }

        for(int i = step; i < S.length; i++){

            current.add(S[i]);

            dfs(result, current, S, capacity, i + 1);

            current.remove(current.size() - 1);

        }

    }

}

 

然后又想到,从1到1,2到1,2,3,不就是在前面的基础上加上一个新元素吗?其实都没必要对所有capacity都做dfs,只要把dfs每次的结果都加入到结果就行了。

public class Solution {

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

        List<List<Integer>> result = new LinkedList<List<Integer>>();

        List<Integer> current = new LinkedList<Integer>();

        //题目没有说S已经排序了

        Arrays.sort(S);

        dfs(result, current, S, 0);

        //补上空集

        result.add(new LinkedList<Integer>());

        return result;

    }

    

    public void dfs(List<List<Integer>> result, List<Integer> current, int[] S, int step){

        if(step == S.length){

            return;

        }

        

        for(int i = step; i < S.length; i++){

            current.add(S[i]);

            result.add(new LinkedList(current));

            dfs(result, current, S, i + 1);

            current.remove(current.size() - 1);

        }

    }

}

 

你可能感兴趣的:(set)