码迷,mamicode.com
首页 > 其他好文 > 详细

排列组合问题

时间:2017-08-26 22:48:19      阅读:213      评论:0      收藏:0      [点我收藏+]

标签:组合   str   utf-8   details   and   number   style   复制   子集   

一.不同元素子集问题

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]]

二.全排列组合

46.Permutations(排列组合)

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].

 

排列组合问题

标签:组合   str   utf-8   details   and   number   style   复制   子集   

原文地址:http://www.cnblogs.com/BetterThanEver-WWCH/p/7436540.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!