# Problem 3-1
###### tags: `week7` `answer`
# permutation
```python=1
def permutation(lst):
if len(lst) == 0:
return []
if len(lst) == 1:
return [lst]
l = []
for i in range(len(lst)):
m = lst[i] #簡單來說,依序選定一個值(10、20...)
remLst = lst[:i] + lst[i+1:] #除了剛剛選的以外的list
for p in permutation(remLst): #先排列剛剛存的list(remLst)
l.append([m] + p) #把剛才每個排列出的都在最前面加上m
return l
n = input()
alist = sorted(input().split(' '))
for p in permutation(alist):
print(p)
```
```python=1
def permutation2(l,p=[]):#l:現在要排列的數字;p:已經排列過的數字
#l.sort()
for i in (l2:=l.copy()):#複製一份l,並在l2中依序選一個數字
p2=p.copy()
p2.extend([i])
if len(l2)>1 and i<len(l2)-1:
l2.remove(i)
permutation2(l2,p2)#l2,p2傳進函數
elif len(l2)>1:permutation2(l[:i],p2)
else:
for i in p2:print(i,end=' ')
print('')
n=int(input())
l=sorted([int(x) for x in input().split()])
```
```python1
#概念基本上跟前一種一樣,只是把已經選過的數字用*d來存
def permutation(n,l,*d):
l.sort()
for i in l:
if n>1:
l2=l.copy()
l2.remove(i)
permutation(n-1,l2,*d,i)
else:print(*d,i)
n=int(input())
l=sorted([int(x) for x in input().split()])
```
> recursion版本
```python=
N = int(input())
numbers = [int(x) for x in input().split()]
final = [numbers]
def rec(myList, n):
global final
temp_list = []
if n == 2:
newList = [myList[1], myList[0]]
return [newList] # len(newList = 2)
else:
newList = [myList]
for i in range(n):
myList[0], myList[i] = myList[i], myList[0]
subList = rec(myList[1:].copy(), n-1)
newList.append([myList[0], *myList[1:]])
for j in range(len(subList)):
x = [myList[0], *subList[j]]
newList.append(x)
if len(newList[0]) == N:
final.extend(newList)
return newList
if N > 2:
a = rec(numbers.copy(), N)
for i in range(len(final)):
final[i] = tuple(final[i])
finalset = set(final)
fin = sorted(finalset, key = lambda x: [x[i] for i in range(N)])
for x in fin:
print(*x, sep=' ')
elif N == 2:
numbers.sort()
print(*numbers, sep = ' ')
numbers.sort(reverse=True)
print(*numbers, sep = ' ')
else:
print(numbers[0])
```