leetcode刷題筆記九十題 子集II
阿新 • • 發佈:2020-07-30
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 } }