2

我有这个char数组:private char[] posibilities = { 'a', 'b', 'c' };

我想要它们的所有可能组合,然后我做了三个嵌套:

for (int cont = 0; cont < posibilities.Length; cont++)
{
    for (int i = 0; i < posibilities.Length; i++)
    {
        for (int j = 0; j < posibilities.Length; j++)
        {
            listBox1.Items.Add(posibilities[cont].ToString() + posibilities[i].ToString() + posibilities[j].ToString());
        }
    }
}

我的问题是:如果我想在我的数组中添加更多字符而不向我的嵌套 for 添加更多 fors,我该怎么做?想象一下,如果我在数组上有 20 个字符,我不能为 20 个字符做......或者这是唯一的方法?

(顺便说一句,我从 3 个月前就一直在尝试解决这个问题,但我仍然不能)

4

2 回答 2

1

试试这种递归方法:

void RecursiveApproach(char[] possibilities, string cur)
{
    if (cur.Length == c.Length)
    {
        listBox1.Items.Add(cur);
        return;
    }
    for (int i = 0; i < possibilities.Length; i++)
    {
        RecursiveApproach(possibilities, cur + possibilities[i]);
    }
}

// Usage
RecursiveApproach(possibilities, "");

如果无法使其全局可见,listBox1 可以作为第三个参数传递给此函数。

但是要小心大量的数字,这个列表会增长得非常快))

于 2012-11-29T20:19:39.900 回答
0
public static IEnumerable<IEnumerable<T>> PermutationsWithRepitition<T>(IList<T> source)
{
    return PermutationsWithRepitition(source, source.Count);
}

//private recursive method that does all of the work.
private static IEnumerable<IEnumerable<T>> PermutationsWithRepitition<T>(IList<T> source, int resultSize)
{
    if (resultSize == 1)
        return source.Select(item => new[] { item });
    else
    {
        return PermutationsWithRepitition(source, resultSize - 1)
            .SelectMany(permutation => source.Select(item => new[]{item}.Concat(permutation)));
    }
}

示例用法:

char[] posibilities = new[] { 'a', 'b', 'c' };

foreach (var permutation in PermutationsWithRepitition(posibilities))
{
    Console.WriteLine(new string(permutation.ToArray()));
}
于 2012-11-29T20:27:36.740 回答