Leetcode 78. Subsets

Posted zhangwj0101

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 78. Subsets相关的知识,希望对你有一定的参考价值。

Question

Given a set of distinct integers, nums, 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 nums = [1,2,3], a solution is:

[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]

Code

递归

public List<List<Integer>> subsets1(int[] S) 
        List<List<Integer>> ret = new ArrayList<List<Integer>>();
        if (S == null) 
            return ret;
        

        Arrays.sort(S);

        dfs(S, 0, new ArrayList<Integer>(), ret);

        return ret;
    

    public void dfs(int[] S, int index, List<Integer> path, List<List<Integer>> ret) 
        ret.add(new ArrayList<Integer>(path));

        for (int i = index; i < S.length; i++) 
            path.add(S[i]);
            dfs(S, i + 1, path, ret);
            path.remove(path.size() - 1);
        
    

位运算方式

 public List<List<Integer>> subsets(int[] nums) 

        Arrays.sort(nums);
        List<List<Integer>> results = new ArrayList<>();
        int len = (int) Math.pow(2, nums.length);
        boolean[] flags = new boolean[nums.length];
        for (int i = 0; i < len; i++) 
            for (int j = 0; j < flags.length; j++) 
                if (!flags[j]) 
                    flags[j] = true;
                    break;
                
                flags[j] = false;
            
            List<Integer> sub = new ArrayList<>();
            for (int j = 0; j < flags.length; j++) 
                if (flags[j]) 
                    sub.add(nums[j]);
                
            
            results.add(sub);
        
        return results;
    

以上是关于Leetcode 78. Subsets的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 78: Subsets

Leetcode 78. Subsets

Leetcode 78. Subsets

[leetcode-78-Subsets]

Leetcode 78: Subsets

LeetCode78. Subsets