views:

558

answers:

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;
}
+1  A: 

You are already calculating combinations in your program. For comb("ABC", 3) there should be one result.

If you want permutations instead (six results), replace s.Substring( i + 1 ) in the recursive function call with s.Substring(0, i) + s.Substring(i+1).

If you want 27 results, simply pass s instead of s.Substring( i + 1 ).

sth
genius!Thank you very much!
ra170