• [leetCode]78. 子集


    [leetCode]78. 子集
    16/100
    保存草稿
    发布文章
    renweiyi1487
    未选择任何文件

    题目

    链接:https://leetcode-cn.com/problems/subsets

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

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

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

    回溯

    回溯法可以将该问题抽象成一棵树,与其他问题(只需添加叶子节点不同)该题需要添加树上的所有节点
    在这里插入图片描述

    class Solution {
    
        private List<List<Integer>> result = new ArrayList<>();
    
        private List<Integer> path = new ArrayList<>();
    
        public List<List<Integer>> subsets(int[] nums) {
            backTracking(nums, 0);
            return result;
        }
    
        private void backTracking(int[] nums, int startIndex) {
            // 收集子集
            result.add(new ArrayList<>(path));
            if (startIndex == nums.length) {
                return;
            }
            for (int i = startIndex; i < nums.length; i++) {
                path.add(nums[i]);
                
                backTracking(nums, i + 1);
                path.remove(path.size() - 1);
            }
        }
    }
    

    题目
    链接:https://leetcode-cn.com/problems/subsets

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

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

    示例:

    输入: nums = [1,2,3]
    输出:
    [
    [3],
    [1],
    [2],
    [1,2,3],
    [1,3],
    [2,3],
    [1,2],
    []
    ]
    回溯
    回溯法可以将该问题抽象成一棵树,与其他问题(只需添加叶子节点不同)该题需要添加树上的所有节点
    在这里插入图片描述

    class Solution {

    private List<List<Integer>> result = new ArrayList<>();
    
    private List<Integer> path = new ArrayList<>();
    
    public List<List<Integer>> subsets(int[] nums) {
        backTracking(nums, 0);
        return result;
    }
    
    private void backTracking(int[] nums, int startIndex) {
        // 收集子集
        result.add(new ArrayList<>(path));
        if (startIndex == nums.length) {
            return;
        }
        for (int i = startIndex; i < nums.length; i++) {
            path.add(nums[i]);
            
            backTracking(nums, i + 1);
            path.remove(path.size() - 1);
        }
    }
    

    }
    Markdown 869 字数 56 行数 当前行 55, 当前列 0 文章已保存19:17:23HTML 627 字数 39 段落

  • 相关阅读:
    滚动条美化插件 nicescroll
    百度地图api
    Echarts的重点
    3月20号课堂随笔
    循环for语句
    有关一些CSS的基本内容
    HTML基本标签和一些注释的问题
    2018年3月17号的随堂笔记
    03.15补习
    for 的相关用法
  • 原文地址:https://www.cnblogs.com/PythonFCG/p/13938534.html
Copyright © 2020-2023  润新知