leetcode刷题笔记九十题 子集II

leetcode刷题笔记九十题 子集II

源地址:90. 子集 II

问题描述:

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

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

示例:

输入: [1,2,2]
输出:
[
[2],
[1],
[1,2,2],
[2,2],
[1,2],
[]
]

/**
本题参考72题回溯方法,其关系类似46 47全排列两道题,需要在回溯的基础进行剪枝,本题剪枝操作主要是在同层剪枝,即nums(i) != nums(i-1)
在进行剪枝的问题上,如果能够画图分析剪枝,能有极大帮助。
*/
import scala.collection.mutable
import util.control.Breaks._
object Solution {
    def subsetsWithDup(nums: Array[Int]): List[List[Int]] = {
        val length = nums.length
        if (length == 0) return List()

        val sortedNums = nums.sorted
        var path = new mutable.ListBuffer[Int]()
        var res  = new mutable.ListBuffer[List[Int]]()

        def dfs(nums: Array[Int], depth: Int, index: Int): Unit = {
            if(path.length == depth){
                res += path.toList
                return
            }
        
            
            for(i <- index to nums.length - (depth - path.length)){
                breakable{
                    if(i > index && nums(i) == nums(i-1)) break()
                    path += nums(i)
                    dfs(nums, depth, i+1)
                    path = path.dropRight(1)
                }
            }
            
           
    }

        for (i <- 1 to length)  dfs(sortedNums, i, 0)
        return List()::res.toList
        
    }

}

猜你喜欢

转载自www.cnblogs.com/ganshuoos/p/13399243.html