C#求所有可能的排列组合

static System.Collections.Specialized.StringCollection MakeStrings(string[] characters, int finalStringLength)
{
    int finalLength = finalStringLength; // The length of the final strings.
    System.Collections.Specialized.StringCollection existingStrings;
    System.Collections.Specialized.StringCollection newStrings =
        new System.Collections.Specialized.StringCollection(); // Start with the all one-letter combinations.
 
    newStrings.AddRange(characters);
 
    for (int len = 2; len <= finalLength; len++)
    {
        // Start a new collection of strings based on the existing strings.
        existingStrings = newStrings;
        newStrings = new System.Collections.Specialized.StringCollection();
 
        // Concatenate every string of length (len-1)...
        foreach (string str in existingStrings)
        {
            // ...with every character...
            foreach (string ch in characters)
            {
                // ...to create every possible string of length len.
                newStrings.Add(str + ch);
            }
        }
    }
    return newStrings;
}

 

posted @ 2014-12-01 17:06  如.若  阅读(1260)  评论(0编辑  收藏  举报