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

78. 子集

时间:2019-08-21 13:26:36      阅读:64      评论:0      收藏:0      [点我收藏+]

标签:lin   子集   bool   ret   length   OLE   subsets   else   link   

技术图片
递归

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

78. 子集

标签:lin   子集   bool   ret   length   OLE   subsets   else   link   

原文地址:https://www.cnblogs.com/cznczai/p/11388115.html

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