-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathPermutationsII.kt
45 lines (38 loc) · 1.02 KB
/
PermutationsII.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
/**
* Given a collection of numbers that might contain duplicates, return all possible unique permutations.
*
* For example,
* [1,1,2] have the following unique permutations:
* [
* [1,1,2],
* [1,2,1],
* [2,1,1]
* ]
*
* Accepted.
*/
class PermutationsII {
fun permuteUnique(nums: IntArray): List<List<Int>> {
val results = mutableListOf<List<Int>>()
if (nums.isEmpty()) {
return results
}
if (nums.size == 1) {
return results.apply {
add(mutableListOf(nums[0]))
}
}
val ints = IntArray(nums.size - 1)
System.arraycopy(nums, 0, ints, 0, nums.size - 1)
val set = mutableSetOf<List<Int>>()
for (list in permuteUnique(ints)) {
for (i in 0..list.size) {
val tmp = mutableListOf<Int>()
tmp.addAll(list)
tmp.add(i, nums[nums.size - 1])
set.add(tmp)
}
}
return results.apply { addAll(set) }
}
}