简繁EN

LeetCodeNo. 006

【LeetCode with Python】 46. Permutations

目錄

題目

原題頁面:https://leetcode.com/problems/permutations/
題目型別:Backtracking
難度評價:Medium
類似題目:(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].


分析

一道遞歸回溯的題目,所以跟大多數遞歸回溯題目類似的解法。只有一點值得注意一下,由於需要從一個集合中挑選出元素,然後下一次遞迴從剩餘的元素中繼續挑選,所以必須能夠記憶和區分出當前已經選出了哪些元素。這裡的做法是每次把選擇的元素與當前列表中第一個元素交換,然後將除第一個元素外的子列表傳遞給下一次遞迴作為其需要處理的當前列表。
另外,a collection of numbers也許是暗示了集合中不會有重複元素?至少對比(M) Permutations II看來,本題的原意應該是沒有重複元素的。


程式碼

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)

本文地址:https://xnerv.wang/zh-tw/leetcode-permutations/