创建可能的字符串组合列表

时间:2010-12-14 20:09:52

标签: .net string

  

可能重复:
  Generate list of all possible permutations of a string

嗨,大家好,

我需要处理一个小算法项目,我需要能够根据给定的限制列出并写入给定文本字符组合的文本文件。

例如,如果我输入字符“a”,“b”和“c”并将限制设置为3,则可能的输出为:

a
b
c
aa
bb
cc
ab
ac
ba
bc
ca
cb
...
    aaa
    bbb
    ccc
    ...
    ...
    abc
    acb
    bac
    bca
    cab
    cba

直到设计出所有可能的组合。

将此文本写入文本文件对我来说没有问题。拥有一个可以编写组合的算法是我不太擅长的。

熟悉.NET(C#或VB)代码。

感谢。

PS

在旁注中,我想知道应用程序创建所有可能的键盘字符的字符串组合以及文件的大小将需要多长时间。

更新: 我还应该显示从n个字符到隐含限制的字符组合。

3 个答案:

答案 0 :(得分:3)

答案 1 :(得分:1)

嗯,对于你的例子,我可能会尝试这样的事情。

string chars = "abc";

for (int a = 0; a < chars.Length; a++)
{
    for (int b = 0; b < chars.Length; b++)
    {
        for (int c = 0; c < chars.Length; c++)
        {
            string row = String.Format("{0}{1}{2}", chars[a], chars[b], chars[c]);
        }
    }
}

这只是在这里打字所以它可能包含错误。另外,我不确定字符限制是否与可能的字符数相关联。但也许这会给你一个起点。

答案 2 :(得分:1)

您可以使用递归实现枚举字符串中的所有排列。快速但功能实现可能如下所示:

编辑:您更改了OP以包含长度小于输入字符集的字符串。以下代码已被修改。它准确地给出了你问题的输出。

static void BuildPermutations(string input, char[] current, int index, int depth, List<string> perms)
{
    if (index == depth)
    {
        perms.Add(new string(current, 0, depth));
        return;
    }
    for (int n = 0; n < input.Length; ++n)
    {
        current[index] = input[n];
        BuildPermutations(input, current, index + 1, depth, perms);
    }
}


static void Main(string[] args)
{
    string input = "abc";
    char[] current = new char[input.Length];
    List<string> perms = new List<string>();
    for (int n = 1; n <= 3; ++n )
        BuildPermutations(input, current, 0, n, perms);
    foreach (string s in perms)
        System.Console.WriteLine(s.ToString());
}
相关问题