zoukankan      html  css  js  c++  java
  • leetcode--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],
      []
    ]
    

    Discuss

    public class Solution {
        public List<List<Integer>> subsets(int[] S) {
           Arrays.sort(S);
    		List<List<Integer> > result = new ArrayList<List<Integer>>();
    		int largest = (int)Math.pow(2, S.length);
    		for(int j = 0; j < largest; ++j){
    			String binary = Integer.toBinaryString(j);
    			List<Integer> aSubSet = new ArrayList<Integer>();
    			int length = binary.length();
    			for(int i = length - 1; i > -1; --i){
    				if(binary.charAt(i) - '0' == 1)
    					aSubSet.add(S[length - 1 - i]);
    			}
    			result.add(aSubSet);
    		}
    		return result;
        }
    }
    

      

     Another method which can be generalized to Subsets II.

    public class Solution {
        public List<List<Integer>> subsets(int[] S) {
           Arrays.sort(S);
    		List<List<Integer> > result = new ArrayList<List<Integer> >();
    		int length = S.length;
    		List<Integer> aSubset = new ArrayList<Integer>();
    		result.add(aSubset);
    		int size = 1;
    		for(int i = 0; i < length; ++i){
    			for(int j = 0; j < size; ++j){
    				List<Integer> newList = new ArrayList<Integer>();
    				newList.addAll(result.get(j));
    				newList.add(S[i]);
    				result.add(newList);
    			}
    			size *= 2;
    		}
    		return result;
        }
    }
    

      

  • 相关阅读:
    2017ICPC南宁补题
    H. The Game of Life
    I
    Twice Equation
    (贪心+队列)String
    Marcin and Training Camp
    莫比乌斯函数模版
    HDU-1695 莫比乌斯反演
    Steps to One DP+莫比乌斯反演
    Educational Codeforces Round 62 (Rated for Div. 2)
  • 原文地址:https://www.cnblogs.com/averillzheng/p/3537222.html
Copyright © 2011-2022 走看看