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

Subsets

时间:2014-12-15 19:10:08      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:leetcode   subsets bit   

一道非常有意思的题目。

原题如下:

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],
  []
]
只记得可以利用位操作来解决这个问题。但是想了一会儿还是没有想起来,就看了下Discuss里面的内容。其中有一个分析十分给力。如下

This is an amazing solution.Learnt a lot.Let me try to explain this to those who didn‘t get the logic. 

Number of subsets for {1 , 2 , 3 } = 2^3 . why ?

case possible outcomes for the set of subsets 

1 -> Take or dont take = 2 

2 -> Take or dont take = 2

3 -> Take or dont take = 2 

therefore , total = 2*2*2 = 2^3 = { { } , {1} , {2} , {3} , {1,2} , {1,3} , {2,3} , {1,2,3} }

Lets assign bits to each outcome -> First bit to 1 , Second bit to 2 and third bit to 3

Take = 1

Dont take = 0

0) 0 0 0 -> Dont take 3 , Dont take 2 , Dont take 1 = { } 

1) 0 0 1 -> Dont take 3 , Dont take 2 , take 1 = {1 } 

2) 0 1 0 -> Dont take 3 , take 2 , Dont take 1 = { 2 } 

3) 0 1 1 -> Dont take 3 , take 2 , take 1 = { 1 , 2 } 

4) 1 0 0 -> take 3 , Dont take 2 , Dont take 1 = { 3 } 

5) 1 0 1 -> take 3 , Dont take 2 , take 1 = { 1 , 3 } 

6) 1 1 0 -> take 3 , take 2 , Dont take 1 = { 2 , 3 } 

7) 1 1 1 -> take 3 , take 2 , take 1 = { 1 , 2 , 3 } 

In the above logic ,Insert S[i] only if (1<<i)&j ==true { j E { 0,1,2,3,4,5,6,7 } i = ith element in the input arra}

element 1 is inserted only into those places where 1st bit of j is 1  if( 1 << i &j ) ==> for above above eg. this is true for sl.no.( j )= 1 , 3 , 5 , 7 

element 2 is inserted only into those places where 2nd bit of j is 1 if( 1 << i &j ) == for above above eg. this is true for sl.no.( j ) = 2 , 3 , 6 , 7

element 3 is inserted only into those places where 3rd bit of j is 1 if( 1 << i &j ) == for above above eg. this is true for sl.no.( j ) = 4 , 5 , 6 , 7 

Time complexity : O(n*2^n) , for every input element loop traverses the whole solution set length i.e. 2^n

感谢 leet_nik 对C=+代码的解释,我对Java代码改动了一下。

如此很容易写出Java代码:

	public List<List<Integer>> subsets(int[] S) {
	    Arrays.sort(S);
	    int totalNumber = 1 << S.length;//将1左移S.length位
	    System.out.println(totalNumber);
	    List<List<Integer>> collection = new ArrayList<List<Integer>>(totalNumber);
	    for (int i=0; i<totalNumber; i++) {
	        List<Integer> set = new LinkedList<Integer>();
	        for (int j=0; j<S.length; j++) {
	            if ((i & (1<<j)) != 0) {
	                set.add(S[j]);	//只添加和i相同的j位置的S[j]
	            }
	        }
	        collection.add(set);
	    }
	    return collection;
	}




Subsets

标签:leetcode   subsets bit   

原文地址:http://blog.csdn.net/ivyvae/article/details/41945703

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