leetcode刷题笔记七十八题 子集

leetcode刷题笔记七十八题 子集

源地址:78. 子集

问题描述:

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

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

示例:

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

/**
本题与前一题组合思路基本一致,使用回溯法
需要注意的是本题是求k = 1 to n 的组合问题即可
*/
import scala.collection.mutable
object Solution {
    def subsets(nums: Array[Int]): List[List[Int]] = {
        val length = nums.length
        if(length == 0) return List()

        val path = mutable.ListBuffer[Int]()
        val res = mutable.ListBuffer[List[Int]]()
        
        for (i <- 1 to length){
            dfs(nums, i, 0, path, res)
        }
    
        return List()::res.toList
    }

    def dfs(nums: Array[Int], depth: Int, index: Int, path: mutable.ListBuffer[Int], res: mutable.ListBuffer[List[Int]]): Unit = {
        if(path.length == depth){
            res += path.toList
            return
        }
        for(i <- index to nums.length - (depth - path.length)){
            path += nums(i)
            dfs(nums, depth, i+1, path, res)
            path -= nums(i)
        }
    }
}
原文地址:https://www.cnblogs.com/ganshuoos/p/13367462.html