1.全排列
#获取全集
def get_all_set(List,cur=0):
global result2
if cur==len(result2) :
print(result2)
return
for each in List:
if each not in result2[:cur]:#如果下一个元素不在前面已经出现的元素里面
result2[cur]=each #把元素加入到result2里面
get_all_set(List=List,cur=cur+1)#寻找下一个元素
if __name__=='__main__':
List=['a','b','c','d']
result2=[None]*len(List)
get_all_set(List=List)
也可以用python的内置模版itertools解决
from itertools import combinations,permutations
if __name__=='__main__':
a = ['a', 'b', 'c', 'd']
print(list(permutations(a, 4)))# 全集
2.子集
#获取List的子集个数
def get_son_set(List):
global result
if len(List)<=2:
return
for i in range(len(List)):
first=List[i]
last=List[:i]+List[i+1:]
if [first] not in result:
result.append([first])
if last not in result:
result.append(last)
get_son_set(List=last)
if __name__=='__main__':
result=[]
get_son_set(List=[1,2,3,4])
print(result)
也可以用python的内置模版itertools解决
from itertools import combinations,permutations
if __name__=='__main__':
for i in range(1,len(a)): #子集
for each in combinations(a,i):
print(list(each))
3.实现的思路大致是dfs,理解后不断将问题拆分,调试代码,然后就很容易做出来了