![Permutations 集合解法[leetcode] Permutations 集合解法[leetcode]](https://i0.wp.com/lazyinwork.com/wp-content/uploads/2022/05/pexels-photo-1925536-1.jpeg?fit=1024%2C682&ssl=1)
Photo by lilartsy on <a href="https://www.pexels.com/photo/person-holding-orange-pen-1925536/" rel="nofollow">Pexels.com</a>
![Permutations 集合解法[leetcode] Permutations 集合解法[leetcode]](https://i0.wp.com/lazyinwork.com/wp-content/uploads/2022/05/pexels-photo-1925536-1-150x150.jpeg?ssl=1)

題目會給你一個不重複的數列,請回傳全部可能的排列方式
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
base = [[n] for n in nums]
#
return_arr = []
while len(base)>0:
unit = base.pop()
#
if len(unit) == len(nums):
return_arr.append(unit)
continue
#
other_nums = set(nums)-set(unit)
for n in other_nums:
base.append(unit+[n])
return return_arr
首先我們先產生一個起始陣列,把每一個元素都當開頭。
base = [[n] for n in nums]
然後依序取出,並添加一個新的元素後,重新加入回起始陣列。
other_nums = set(nums)-set(unit)
for n in other_nums:
base.append(unit+[n])
除了這個方式以外,也可以使用遞迴來解題。