Listing all permutations of a string/integer

后端 未结 29 1975
没有蜡笔的小新
没有蜡笔的小新 2020-11-22 00:44

A common task in programming interviews (not from my experience of interviews though) is to take a string or an integer and list every possible permutation.

Is there

29条回答
  •  迷失自我
    2020-11-22 01:35

    Here is a C# answer which is a little simplified.

    public static void StringPermutationsDemo()
    {
        strBldr = new StringBuilder();
    
        string result = Permute("ABCD".ToCharArray(), 0);
        MessageBox.Show(result);
    }     
    
    static string Permute(char[] elementsList, int startIndex)
    {
        if (startIndex == elementsList.Length)
        {
            foreach (char element in elementsList)
            {
                strBldr.Append(" " + element);
            }
            strBldr.AppendLine("");
        }
        else
        {
            for (int tempIndex = startIndex; tempIndex <= elementsList.Length - 1; tempIndex++)
            {
                Swap(ref elementsList[startIndex], ref elementsList[tempIndex]);
    
                Permute(elementsList, (startIndex + 1));
    
                Swap(ref elementsList[startIndex], ref elementsList[tempIndex]);
            }
        }
    
        return strBldr.ToString();
    }
    
    static void Swap(ref char Char1, ref char Char2)
    {
        char tempElement = Char1;
        Char1 = Char2;
        Char2 = tempElement;
    }
    

    Output:

    1 2 3
    1 3 2
    
    2 1 3
    2 3 1
    
    3 2 1
    3 1 2
    

提交回复
热议问题