一.不同元素子集问题
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].
时间: 2024-10-26 05:13:38