leetcode 78题子集

题目:

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

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

示例:

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

思路:

和求组合求和一样,求数组的相关的题目可以把题目解析为一棵树,或者森林就好理解了;

比如本题:

从1开始,存在1,12,13,123 四种

从2开始存在 2,23 两种

从3开始,存在3一种

是不是就是三个数组成的森林?

然后思路来了,以每个节点为根遍历数组,把当前节点放入结果集,然后以下一个节点为根继续遍历

使用递归实现,别人把这个过程叫回溯,就是比如:第一次1为根节点,加入结果集result[0] 这是第一层,下一步 1,2加入结果集这是第二层,然后第三层,四层。。。但是还需要返回1,3这个节点递归,所以这里叫回溯。一般的还会和剪枝一起使用,所以下面代码的start就是剪枝

代码

public class 子集 {
    public static List<List<Integer>>  subsets(int[] nums) {
        List<List<Integer>> results = new ArrayList<>();
        solation(0, new ArrayList<>(), nums, results);
        return results;
    }

    /**
     * 第一步:每个节点作为一个树的根,然后根的子节点就是大于本节点的其他的节点
     * 第二步:每个节点都可以作为根节点,但是不需要重新遍历之前的节点了
     * 第三部:回溯实现,每个节点
     */
    public static void solation(int start, List<Integer> temp, int[] nums, List<List<Integer>> results) {
        results.add(new ArrayList<>(temp));
        //以每个节点为根遍历数组
        for (int i = start; i < nums.length; i++) {
            temp.add(nums[i]);
            solation(i + 1, temp, nums, results);
            temp.remove(temp.size() - 1);
        }
    }
    public static void main(String[] args){
        int[] candidates ={1,2,3};
        List<List<Integer>> result =  子集.subsets(candidates);
        for(List i:result){
            for(int j =0;j< i.size();j++){
                System.out.print(i.get(j));
            }
            System.out.println("");
        }
    }
}

 

发布了23 篇原创文章 · 获赞 4 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq1076472549/article/details/103744808
今日推荐