Key Idea
- Iterate through
nums
- While traversing, store the element in the
path
. Then, initialize newNums
with the remaining nums
after excluding the current element, and recursively call DFS with newNums
as the new set of numbers to consider.
- The escape condition is when the length of
nums
becomes 0.
- After returning from the recursion, restore the previous state of the operation using
pop()
.
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
def dfs(nums, path):
if len(nums) == 0:
result.append(path.copy())
return
for i in range(len(nums)):
path.append(nums[i])
newNums = [value for index, value in enumerate(nums) if index != i]
dfs(newNums, path)
path.pop()
result = []
dfs(nums, [])
return result