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

      

  • 相关阅读:
    线性筛2 筛约数个数
    背包板子
    线段树(指针板子)
    10.11 模拟赛(QBXT国庆Day3)
    10.6 体育成绩统计
    10.5 T3 DDP BZOJ 4712
    10.2模拟赛总结
    线性筛1
    CF165D Beard Graph
    2019 CSP-S第一轮(hsyz半日游)
  • 原文地址:https://www.cnblogs.com/averillzheng/p/3537222.html
Copyright © 2011-2022 走看看