Problem
Problem page: https://leetcode.com/problems/permutations/
Topics: Backtracking
Difficulty: Medium
Similar problems: (M) Next Permutation, (M) Permutations II, (M) Permutation Sequence, (M) Combinations
Given a collection of numbers, return all possible permutations.
For example,
[1,2,3]have the following permutations:
[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2], and[3,2,1].
Analysis
This is a recursive backtracking problem, so the solution looks much like the one for most problems of this kind. There's just one thing to watch out for. Each time I pick an element from the collection, the next recursive call has to pick from the remaining elements, so I need to keep track of which ones I've already picked. I swap the element I pick with the first element in the current list, then pass the sublist after the first element to the next recursive call as its current list.
Also, maybe "a collection of numbers" hints that the collection has no duplicates? At least judging by (M) Permutations II, I think the intent here was that the elements are all distinct.
Code
1 | class Solution: |
Article link: https://xnerv.wang/en/leetcode-permutations/
