forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0090-subsets-ii.kt
27 lines (24 loc) · 918 Bytes
/
0090-subsets-ii.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
fun subsetsWithDup(nums: IntArray): List<List<Int>> {
nums.sort()
val resultantList = mutableListOf<List<Int>>()
val intermediaryList = mutableListOf<Int>()
fun dfs(decisionIndex: Int = 0) {
if (decisionIndex > nums.lastIndex) {
resultantList.add(intermediaryList.toList())
return
}
// decision to include nums[decisionIndex]
intermediaryList.add(nums[decisionIndex])
dfs(decisionIndex + 1)
// decision to not include nums[decisionIndex]
intermediaryList.removeAt(intermediaryList.lastIndex)
// skipping duplicates if any
var i = decisionIndex
while ((i in nums.indices && i + 1 in nums.indices) && nums[i] == nums[i + 1]) i++
dfs(i + 1)
}
dfs()
return resultantList
}
}