zoukankan      html  css  js  c++  java
  • 78. 子集


    递归

    class Solution {
    	private List ls; 
    	private boolean []bool;
    	private int n;
    	public List<List<Integer>> subsets(int[] nums) {
    		n = nums.length;
    		ls = new LinkedList<LinkedList>();
            if(n==0)return ls;
    		bool = new boolean [n];
            dfs(nums,0,bool);
    		return ls;
    	}
    	public void dfs(int nums[],int u,boolean bool[]) {
    		if(u==n) {
    			LinkedList path = new LinkedList<LinkedList>();
    			for(int i = 0 ; i< n ;i++) {
    				if(bool[i]==false)
    					path.add(nums[i]);
    			}
    			ls.add(path);
    		}
    		else {
    			bool[u]= true;
                dfs( nums,u+1,bool);
                bool[u] = false;
                dfs( nums,u+1,bool);
    		}
    	}
    
    }
    

    回溯+二进制

    class Solution {
    	private List ls;
    	private boolean[] bool;
    	private int n;
    
    	public List<List<Integer>> subsets(int[] nums) {
    		n = nums.length;
    		ls = new LinkedList<LinkedList>();
    		bool = new boolean[n];
    		for (int i = 0; i < Math.pow(2, n); i++) {
    			LinkedList path = new LinkedList<LinkedList>();
    			String s = Integer.toBinaryString(i);
    			while(s.length()!=n) s = '0'+s;
    			for (int x = 0; x < n; x++)
    				if (s.charAt(x) == '1')
    					path.add(nums[x]);
    			ls.add(path);
    		}
    		return ls;
    	}
    }
    
  • 相关阅读:
    java8学习
    linux常用命令
    window操作系统分区
    java8特性
    mysql索引本质
    红黑树
    http请求传参问题解决
    老王说架构
    从URL到看到网页的过程
    RabbitMQ如何工作和RabbitMQ核心概念
  • 原文地址:https://www.cnblogs.com/cznczai/p/11388115.html
Copyright © 2011-2022 走看看