首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何列出字符串/整数的所有排列?

如何列出字符串/整数的所有排列?
EN

Stack Overflow用户
提问于 2018-02-11 00:11:51
回答 2查看 0关注 0票数 0

如何列出字符串/整数的所有排列?

EN

回答 2

Stack Overflow用户

发布于 2018-02-11 08:14:35

我在http://www.programmersheaven.com/mb/Algorithms/369713/369713/permutation-algorithm-help/上找到了伪代码

代码语言:javascript
复制
makePermutations(permutation) {
  if (length permutation < required length) {
    for (i = min digit to max digit) {
      if (i not in permutation) {
        makePermutations(permutation+i)
      }
    }
  }
  else {
    add permutation to list
  }
}
票数 0
EN

Stack Overflow用户

发布于 2018-02-11 09:34:51

这是我的通用函数,它可以从T列表中返回所有排列(不是组合):

代码语言:javascript
复制
static IEnumerable<IEnumerable<T>>
    GetPermutations<T>(IEnumerable<T> list, int length)
{
    if (length == 1) return list.Select(t => new T[] { t });

    return GetPermutations(list, length - 1)
        .SelectMany(t => list.Where(e => !t.Contains(e)),
            (t1, t2) => t1.Concat(new T[] { t2 }));
}

例:

代码语言:javascript
复制
IEnumerable<IEnumerable<int>> result =
    GetPermutations(Enumerable.Range(1, 3), 3);

输出 - 整数列表的列表:

代码语言:javascript
复制
{1,2,3} {1,3,2} {2,1,3} {2,3,1} {3,1,2} {3,2,1}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/-100003482

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档