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)
        }
    }
    
  • 相关阅读:
    Python if __name__ == "__main__" 的含义
    自己用
    phpstorm && pycharm
    API Design for C++ 一本书值得一看
    std::set 使用
    Using Windows Web Services
    SOA 好好了解下
    NI Measurement Studio Enterprise 8.6
    那天看看
    内存映射 那天自己改改
  • 原文地址:https://www.cnblogs.com/zhongju/p/13894864.html
Copyright © 2011-2022 走看看