Leetcode 子集

子集

题目描述:

给你一个整数数组 nums ,数组中的元素 互不相同。返回该数组所有可能的子集(幂集)。
解集 不能包含重复的子集。你可以按 任意顺序返回解集。
提示:
   1 <= nums.length <= 10
   -10 <= nums[i] <= 10
   nums 中的所有元素 互不相同

题目链接

class Solution {
    
    
    private int[] nums;
    private List<List<Integer>> result;
    private List<Integer> temp;
    private int len;
    public List<List<Integer>> subsets(int[] nums) {
    
    
        // 初始化
        this.nums = nums;
        this.len = nums.length;
        this.result = new ArrayList<List<Integer>>();
        this.temp = new ArrayList<Integer>();
        DFS(0); 
        return result;
    }
    /**
    * 参数表示已经遍历过的元素个数
    **/
    private void DFS(int count){
    
    
        if(count == len){
    
    
            this.result.add(new ArrayList<Integer>(this.temp));
            return;
        }
        // 选择当前的元素
        this.temp.add(this.nums[count]);
        DFS(count+1);
        // 不选择当前的元素
        this.temp.remove(this.temp.size() - 1);
        DFS(count+1);
    }
}

典型的深度优先搜索算法简单应用,这里对于nums数组中的每个元素,只有两种情况:选择和不选择。详细请看代码,读者有疑问的地方欢迎留言。

猜你喜欢

转载自blog.csdn.net/weixin_43914658/article/details/113818584