Listing all permutations of a string/integer

后端 未结 29 2720
没有蜡笔的小新
没有蜡笔的小新 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 simple solution in c# using recursion,

    void Main()
    {
        string word = "abc";
        WordPermuatation("",word);
    }
    
    void WordPermuatation(string prefix, string word)
    {
        int n = word.Length;
        if (n == 0) { Console.WriteLine(prefix); }
        else
        {
            for (int i = 0; i < n; i++)
            {
                WordPermuatation(prefix + word[i],word.Substring(0, i) + word.Substring(i + 1, n - (i+1)));
            }
        }
    }
    

提交回复
热议问题