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
Prev Previous commit
Next Next commit
Update 0046-permutations.kt
  • Loading branch information
FilipeLipan committed May 1, 2023
commit 127b734d8db169defd86a2108da9b99df3fffc85
17 changes: 6 additions & 11 deletions kotlin/0046-permutations.kt
Original file line number Diff line number Diff line change
@@ -1,25 +1,20 @@
class Solution {
fun permute(nums: IntArray): List<List<Int>> {
val res = mutableListOf<List<Int>>()
val queue = ArrayDeque<Int>()

for (num in nums) {
queue.add(num)
}
fun permute(nums: IntArray): List<MutableList<Int>> {
val res = mutableListOf<MutableList<Int>>()
val queue = ArrayDeque<Int>(nums.toList())

// base case
if (queue.size == 1) {
return listOf(queue.toList()) // queue.toList() is a deep copy
return listOf(queue.toMutableList()) // queue.toList() is a deep copy
}

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)
perm.add(n)
res.add(perm)
}
queue.addLast(n)
}
Expand Down