Listing all permutations of a string/integer

后端 未结 29 2722
没有蜡笔的小新
没有蜡笔的小新 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:26

    Here I have found the solution. It was written in Java, but I have converted it to C#. I hope it will help you.

    Enter image description here

    Here's the code in C#:

    static void Main(string[] args)
    {
        string str = "ABC";
        char[] charArry = str.ToCharArray();
        Permute(charArry, 0, 2);
        Console.ReadKey();
    }
    
    static void Permute(char[] arry, int i, int n)
    {
        int j;
        if (i==n)
            Console.WriteLine(arry);
        else
        {
            for(j = i; j <=n; j++)
            {
                Swap(ref arry[i],ref arry[j]);
                Permute(arry,i+1,n);
                Swap(ref arry[i], ref arry[j]); //backtrack
            }
        }
    }
    
    static void Swap(ref char a, ref char b)
    {
        char tmp;
        tmp = a;
        a=b;
        b = tmp;
    }
    

提交回复
热议问题