简繁EN

LeetCodeNo. 006

[LeetCode with Python] 46. Permutations

Contents

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution:
def doPermute(self, num_list):
if 1 == len(num_list):
return [ num_list ]
res_list = [ ]
for i in range(0, len(num_list)):
num_list[0], num_list[i] = num_list[i], num_list[0]
sub_res_list = self.doPermute(num_list[1:])
list_head = [ num_list[0] ]
new_list = [ list_head + list for list in sub_res_list]
res_list.extend(new_list)
return res_list

# @param num, a list of integer
# @return a list of lists of integers
def permute(self, num):
return self.doPermute(num)

Article link: https://xnerv.wang/en/leetcode-permutations/