-1

Why doesn't this produce the correct number of string permutations? For

perm("ABC", 3)

it should print 27 different permutations.

private static List<string> permutated = new List<string>(30000);

public static List<string> perm(string s, int k) { return comb(s, "", k); }

private static List<string> perm(string s, string prefix, int k)
{
    if (k == 0)
    {
        permutated.Add(prefix);
    }
    else 
    {
        for (int i = 0; i < s.Length; i++)
        {
            perm( s.Substring( i + 1 ), prefix + s[i], k - 1 );
        }
    }
    return permutated;
}
4

1 回答 1

2

您已经在程序中计算组合。因为comb("ABC", 3)应该有一个结果。

如果您想要置换(六个结果),s.Substring( i + 1 )请在递归函数调用中替换为s.Substring(0, i) + s.Substring(i+1).

如果您想要 27 个结果,只需传递s而不是s.Substring( i + 1 ).

于 2009-04-16T22:03:43.003 回答