子集

2022-07-27

题目:给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。

说明:解集不能包含重复的子集。

示例:

输入: nums = [1,2,3]
输出:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]

这种求多种组合的问题,明显是可以用回溯方法的,

其实回溯算法关键在于: 不合适就退回上一步

然后通过约束条件, 减少时间复杂度.

Java代码如下:

class Solution {
     public List<List<Integer>> subsets(int[] nums) {
            List<List<Integer>>  result = new ArrayList<>();
            pushBack(0,nums.length-1,nums,result,new ArrayList<>());
            return result;
    }

    public void pushBack(int start,int end,int[] nums,List<List<Integer>> result,List<Integer>  tmp){
        result.add(new ArrayList<>(tmp));

        for(int i=start;i<=end;i++){
            tmp.add(nums[i]);
            pushBack(i+1,end,nums,result,tmp);
            tmp.remove(tmp.size()-1);
        }

    }
}

本文地址:https://blog.csdn.net/qq_33775774/article/details/110244503

《子集.doc》

下载本文的Word格式文档,以方便收藏与打印。