-
Notifications
You must be signed in to change notification settings - Fork 20
/
SubsetsII.kt
56 lines (45 loc) · 1.07 KB
/
SubsetsII.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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/**
* Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set).
*
* Note: The solution set must not contain duplicate subsets.
*
* For example,
* If nums = [1,2,2], a solution is:
*
* [
* [2],
* [1],
* [1,2,2],
* [2,2],
* [1,2],
* []
* ]
*
* Accepted.
*/
class SubsetsII {
fun subsetsWithDup(nums: IntArray): List<List<Int>> {
if (nums.isEmpty()) {
return emptyList()
}
val lists = mutableListOf<List<Int>>()
if (nums.size == 1) {
// Add the empty list.
lists.add(emptyList())
lists.add(listOf(nums[0]))
return lists
}
nums.sort()
for (list in subsetsWithDup(nums.copyOfRange(0, nums.size - 1))) {
val l = mutableListOf(nums[nums.size - 1])
l.addAll(list)
if (!lists.contains(l)) {
lists.add(l)
}
if (!lists.contains(list)) {
lists.add(list)
}
}
return lists
}
}