Problem
Given an arraynums of distinct integers, return all the possible permutations. You can return the answer in any order.
Examples
Constraints
- 1 <= nums.length <= 6
- -10 <= nums[i] <= 10
- All the integers of nums are unique.
Documentation Index
Fetch the complete documentation index at: /llms.txt
Use this file to discover all available pages before exploring further.
Tested Python solution for LeetCode 46 with 12 pytest cases. Generate a practice environment with lcpy.
lcpy gen -n 46 # by problem number
lcpy gen -s permutations # by problem name
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]]
class Solution:
# Time: O(n! * n)
# Space: O(n! * n) output + O(n) recursion
def permute(self, nums: list[int]) -> list[list[int]]:
result = []
def backtrack(start: int) -> None:
if start == len(nums):
result.append(nums[:])
return
for i in range(start, len(nums)):
nums[start], nums[i] = nums[i], nums[start]
backtrack(start + 1)
nums[start], nums[i] = nums[i], nums[start]
backtrack(0)
return result
| Time | Space |
|---|---|
| O(n! * n) | O(n! * n) output + O(n) recursion |