leetcode-78. 子集

78. 子集

题目

给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。

解集 不能 包含重复的子集。你可以按 任意顺序 返回解集。

分析

回溯的经典题

第一种方法是在for循环中进行递归。不过需要判断当前track是否包含遍历时的元素nums[i],若存在则continue。

第二种方法中结束条件为到达数组末尾。

代码

public List<List<Integer>> result = new ArrayList<>();
public List<List<Integer>> subsets(int[] nums) {
    List<Integer> track = new ArrayList<>();
    backtrack(nums, track, 0);
    return result;
}

public void backtrack(int[] nums, List<Integer> track, int index){
    result.add(new ArrayList(track));
    for(int i=index;i<nums.length;i++){
        if(track.contains(nums[i])){
            continue;
        }
        track.add(nums[i]);
        backtrack(nums, track, i);
        track.remove(track.size()-1);
    }
}
List<List<Integer>> result = new ArrayList<List<Integer>>();
List<Integer> track = new ArrayList<Integer>();
public List<List<Integer>> subsets(int[] nums) {
    backtrack(nums, 0);
    return result;
}

public void backtrack(int[] nums, int index){
    if(index==nums.length){
        result.add(new ArrayList<Integer>(track));
        return;
    }
    track.add(nums[index]);
    backtrack(nums, index+1);
    track.remove(track.size()-1);
    backtrack(nums, index+1);
}

结果

时间超过100%

内存超过44%


版权声明:本文为Stack_Alan原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。