Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Update 0046-permutations.kt
  • Loading branch information
FilipeLipan committed May 1, 2023
commit 455ce9c239c3c6c0b35a7376dec8132c7d62708b
34 changes: 19 additions & 15 deletions kotlin/0046-permutations.kt
Original file line number Diff line number Diff line change
@@ -1,24 +1,28 @@
class Solution {
fun permute(nums: IntArray): List<List<Int>> {
val res = mutableListOf<List<Int>>()
permute(nums, mutableSetOf<Int>(), mutableListOf<Int>(), res)
return res
}
val queue = ArrayDeque<Int>()

for (num in nums) {
queue.add(num)
}

fun permute(nums: IntArray, set: MutableSet<Int>, list: MutableList<Int>, res: MutableList<List<Int>>) {
if (list.size == nums.size) {
res.add(ArrayList(list))
return
// base case
if (queue.size == 1) {
return listOf(queue.toList()) // queue.toList() is a deep copy
}

for (i in 0..nums.size-1) {
if (!set.contains(nums[i])) {
list.add(nums[i])
set.add(nums[i])
permute(nums, set, list, res)
list.removeAt(list.size-1)
set.remove(nums[i])
for (i in nums.indices) {
val n = queue.removeFirst()
val perms = permute(queue.toIntArray())

for (perm in perms) {
val mutablePerm = perm.toMutableList()
mutablePerm.add(n)
res.add(mutablePerm)
}
queue.addLast(n)
}
return res
}
}
}