码迷,mamicode.com
首页 > 其他好文 > 详细

Subsets

时间:2015-03-19 21:53:20      阅读:167      评论:0      收藏:0      [点我收藏+]

标签:

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);
        }
    }
}

 

Subsets

标签:

原文地址:http://www.cnblogs.com/NickyYe/p/4351652.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!