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

[LeetCode 78] Subsets

时间:2015-03-28 08:50:46      阅读:100      评论:0      收藏:0      [点我收藏+]

标签:java   leetcode   算法   

题目链接:subsets


import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

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

public class Subsets {

//	10 / 10 test cases passed.
//	Status: Accepted
//	Runtime: 218 ms
//	Submitted: 0 minutes ago

	//时间复杂度O(2^n) 空间复杂度 O(n)

	public List<List<Integer>> subsets = new ArrayList<List<Integer>>();
    public List<List<Integer>> subsets(int[] S) {
        Arrays.sort(S);
        subsets(S, 0, new ArrayList<Integer>());
        return subsets;        
    }
    public void subsets(int[] S, int step, List<Integer> subset) {
        if(step == S.length) {
        	subsets.add(subset);
        	return;
        }
        
        //S[step] 不加入子集中
        subsets(S, step + 1, new ArrayList<Integer>(subset));
        
        //S[step] 加入子集中
        subset.add(S[step]);        
        subsets(S, step + 1, new ArrayList<Integer>(subset));        
    }

//input		{1 , 3, 2}  
    
// output
//    		[]
//    		[3]
//    		[2]
//    		[2, 3]
//    		[1]
//    		[1, 3]
//    		[1, 2]
//    		[1, 2, 3]
    
	public static void main(String[] args) {


	}

}


[LeetCode 78] Subsets

标签:java   leetcode   算法   

原文地址:http://blog.csdn.net/ever223/article/details/44688193

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