Loading

[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)
    }
}
posted @ 2020-10-29 09:12  Zhongju.copy()  阅读(87)  评论(0编辑  收藏  举报