An interactive visualization of the backtracking approach to generate all permutations. Watch the decision tree grow as unused elements are tried at each position.
Backtracking LeetCode 46 โ MediumGiven an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.
Input: nums = [1,2,3] Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
Input: nums = [0,1] Output: [[0,1],[1,0]]
Input: nums = [1] Output: [[1]]
fun permute(nums: IntArray): List<List<Int>> {
val result = mutableListOf<List<Int>>()
fun backtrack(current: MutableList<Int>) {
if (current.size == nums.size) {
result.add(current.toList())
return }
for (num in nums) {
if (num !in current) {
current.add(num)
backtrack(current)
current.removeLast()
} } }
backtrack(mutableListOf())
return result }
The backtracking approach to generating permutations explores all possible orderings by building permutations one element at a time. At each position, we try every element that hasn't been used yet, recurse to fill the remaining positions, then backtrack to try other possibilities.
O(n! ร n) โ There are n! permutations to generate, and each one takes O(n) time to construct and copy.
O(n! ร n) โ Storing all n! permutations, each of length n. The recursion depth is O(n).