c# - 使用相同字母的排列

标签 c# algorithm permutation

我目前正在做一个项目,我需要从给定的一组字符中生成所有可能的排列。我目前正在使用此代码:

public static IEnumerable<string> AllPermutations(this IEnumerable<char> s)
{
    return s.SelectMany(x =>
    {
        var index = Array.IndexOf(s.ToArray(), x);
        return s.Where((y, i) => i != index).AllPermutations().Select(y => new string(new[] { x }.Concat(y).ToArray())).Union(new[] { new string(new[] { x }) });
    }).Distinct();
}

来自 this回答。

我遇到的问题是它不会生成多次使用同一字母的排列。

例如,如果我使用 abcde 作为输入,我需要它来生成像 aaaaadcc 等组合

我对 LINQ 的经验不足,无法理解代码在何处停止重复字母。非常感谢任何帮助。

最佳答案

可能有效,但我确信它可以更有效地完成(从 PeskyGnat 获取计数提示):

    static IEnumerable<string> GetVariations(string s)
    {
        int[] indexes = new int[s.Length];
        StringBuilder sb = new StringBuilder();

        while (IncrementIndexes(indexes, s.Length))
        {
            sb.Clear();
            for (int i = 0; i < indexes.Length; i++)
            {
                if (indexes[i] != 0)
                {
                    sb.Append(s[indexes[i]-1]);
                }
            }
            yield return sb.ToString();
        }
    }

    static bool IncrementIndexes(int[] indexes, int limit)
    {
        for (int i = 0; i < indexes.Length; i++)
        {
            indexes[i]++;
            if (indexes[i] > limit)
            {
                indexes[i] = 1;
            }
            else
            {
                return true;
            }
        }
        return false;
    }

编辑:根据 Rawlings 的建议更改为使用 yield 返回。如果您不需要保留所有结果并且可以在结果全部生成之前就开始使用它们,那么内存使用会好得多。

关于c# - 使用相同字母的排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9635076/

相关文章:

c# - 枚举表单上的控件

c# - 字符串未被识别为 Windows Server 2016 上的有效日期时间

找到最佳数量的拉米风格集的算法?

python - 有没有办法置换矩阵的子集?

Python Secret Santa 程序——如何获得更高的成功率

javascript - 置换字符串直到它匹配一些输入?

c# - 在抛出未处理的 JavaScript 错误之前,不查询 IServiceProvider IElementBehaviorFactory

c# - 当其他应用程序的用户登录问题 C# 时用户注销

python - 计算我的函数的大 o

.net - 压缩 SQL 的冗余文本数据。固定词典?