1、题目
对字符数组进行全排列。
示例1::['a','b','c'],
排列后为:[['a', 'b', 'c'], ['a', 'c', 'b'], ['b', 'a', 'c'], ['b', 'c', 'a'], ['c', 'a', 'b'], ['c', 'b', 'a']]
2、python代码
def permute(nums):
"""思路
如果数组为空,返回空列表。
如果数组长度为1,返回包含这个元素的单个列表。
否则,对于数组中的每个元素:
将该元素从数组中移除,生成剩余元素的全排列。
将该元素插入到生成的每个排列的所有可能位置,生成新的排列。
"""
len_nums = len(nums)
if len_nums == 0:
return []
elif len_nums == 1:
return [nums]
res = []
for i in range(0, len_nums):
cur = nums[i]
remains = nums[:i] + nums[i + 1:]
for j in permute(remains):
res = res.append([cur] + j)
return res