Listing all permutations of a string/integer

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

    Here is the function which will print all permutaion. This function implements logic Explained by peter.

    public class Permutation
    {
        //http://www.java2s.com/Tutorial/Java/0100__Class-Definition/RecursivemethodtofindallpermutationsofaString.htm
    
        public static void permuteString(String beginningString, String endingString)
        {           
    
            if (endingString.Length <= 1)
                Console.WriteLine(beginningString + endingString);
            else
                for (int i = 0; i < endingString.Length; i++)
                {
    
                    String newString = endingString.Substring(0, i) + endingString.Substring(i + 1);
    
                    permuteString(beginningString + endingString.ElementAt(i), newString);
    
                }
        }
    }
    
        static void Main(string[] args)
        {
    
            Permutation.permuteString(String.Empty, "abc");
            Console.ReadLine();
    
        }
    

提交回复
热议问题