算法 - 排列组合 [英] Algorithms - Combinations and Permutations

查看:109
本文介绍了算法 - 排列组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个HWK问题,显然也是一个常见的​​面试问题,我遇到麻烦:

A hwk question and apparently also a common interview question I'm having trouble with:

写一个算法(伪code)在打印出的一组n个元素的三要素全部子集。本集的元素存储在一个列表,是输入到算法。

"Write an algorithm (pseudocode) that prints out all the subsets of three elements of a set of n elements. The elements of this set are stored in a list that is the input to the algorithm."

因此​​,举例来说,如果S = {1,2,3,4}算法将打印出这四种组合:

So for example if S = {1,2,3,4} the algorithm would print out these four combinations:

123 124 134 234

123 124 134 234

任何人都可以提供他们的想法/解决方案?

Can anyone offer their thoughts / a solution?

推荐答案

递归:

def subset (prefix, list, count):
    if count is 0:
        print prefix
        return
    for each element in list:
        subset (prefix & element, list beyond element, count - 1)

subset ("", {1,2,3,4}, 3)

一个Python的概念证明:

A Python proof of concept:

def subset (prefix, list, count):
    if count is 0:
        print prefix
        return
    for i in range (len(list)):
        subset ("%s%s"%(prefix,list[i]), list[i+1:], count - 1)

subset ("", "1234", 3)

它输出,为输入字符串的各种值(第二个参数子集):

123456   12345   1234   123   12
------   -----   ----   ---   --
123      123     123    123
124      124     124
125      125     134
126      134     234
134      135
135      145
136      234
145      235
146      245
156      345
234
235
236
245
246
256
345
346
356
456

这篇关于算法 - 排列组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆