一.不同元素子集问题
78. Subsets
Given a set of distinct integers, nums, return all possible subsets.
给定一组非重复数字,求出所有可能的子集
解析:
例如 [1,2,3],解法:
首先放[],然后往已有的[]中放1
1. 首先放1
此时已有[ [], 1 ]
2. 然后对[ [], 1 ] 放2
于是此时有 [ [], [1], [2], [1,2] ]
3. 然后对[ [], [1], [2], [1,2] ] 放3
此时[ [], [1], [2], [1,2], [3], [1,3], [2,3], [1,2,3] ] 求出解
#encoding:utf-8
_author_ = "Wang Wenchao"
def fun(ls):
result=[]
st=[]
result.append(st)
for i in ls:
for j in range(len(result)):
x=result[j][:] #复制列表
x.append(i)
result.append(x)
return result
ls=[1,2,3]
print fun(ls)
运行结果 [[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]
二.全排列组合
Permutations
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].
#encoding:utf-8
_author_ = "Wang Wenchao"
count=0
def perm(ls,begin,end):
global count
if begin>=end:
print ls
count+=1
else:
i=begin
for num in range(begin,end):
ls[num],ls[i]=ls[i],ls[num]
perm(ls,begin+1,end)
ls[num], ls[i] = ls[i], ls[num]#回溯
ls = [1, 2,3]
perm(ls,0,len(ls))
print count
结果:
[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, 3, 1]
[3, 2, 1]
[3, 1, 2]
6
三.如果带有重复元素
则需要一个判断条件
#encoding:utf-8
_author_ = "Wang Wenchao"
count=0
def perm(ls,begin,end):
global count
if begin>=end:
print ls
count+=1
else:
i=begin
for num in range(begin,end):
if ls[num] not in ls[begin:num]:
ls[num],ls[i]=ls[i],ls[num]
perm(ls,begin+1,end)
ls[num], ls[i] = ls[i], ls[num]#回溯
ls = [3,1,1,1]
perm(ls,0,len(ls))
print count
运行结果:
[3, 1, 1, 1]
[1, 3, 1, 1]
[1, 1, 3, 1]
[1, 1, 1, 3]
4