zoukankan      html  css  js  c++  java
  • [LeetCode] 78. Subsets(子集)

    Description

    Given a set of distinct integers, nums, return all possible subsets (the power set).
    给定一个互异的整数集合 nums,返回所有可能的子集(幂集)。

    Note

    The solution set must not contain duplicate subsets.
    最后的结果不能包含重复的子集。

    Example

    Input: nums = [1,2,3]
    Output:
    [
      [3],
      [1],
      [2],
      [1,2,3],
      [1,3],
      [2,3],
      [1,2],
      []
    ]
    

    Solution

    又是一道回溯法的例题,上次做到回溯法的题目是排列树,这次的例题则是回溯法的第二种情况:组合树,具体不多说,直接上代码:

    class Solution {
        private val result = arrayListOf<List<Int>>()
    
        fun subsets(nums: IntArray): List<List<Int>> {
            backtrack(arrayListOf(), nums, 0)
            return result
        }
    
        private fun backtrack(current: MutableList<Int>, nums: IntArray, curIndex: Int) {
            if (curIndex == nums.size) {
                result.add(ArrayList(current))
                return
            }
            current.add(nums[curIndex])
            backtrack(current, nums, curIndex + 1)
            current.removeAt(current.lastIndex)
            backtrack(current, nums, curIndex + 1)
        }
    }
    
  • 相关阅读:
    monit官方摘录
    monit配置文件
    monit检测语法
    monit介绍和配置
    ganglia-gmond.conf配置文件
    ganglia问题汇总
    ganglia使用nagios告警
    ganglia-gmetad 配置文件
    监控项目
    监控方案
  • 原文地址:https://www.cnblogs.com/zhongju/p/13894864.html
Copyright © 2011-2022 走看看