Listing all permutations of a string/integer

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

    Here is an easy to understand permutaion function for both string and integer as input. With this you can even set your output length(which in normal case it is equal to input length)

    String

        static ICollection result;
    
        public static ICollection GetAllPermutations(string str, int outputLength)
        {
            result = new List();
            MakePermutations(str.ToCharArray(), string.Empty, outputLength);
            return result;
        }
    
        private static void MakePermutations(
           char[] possibleArray,//all chars extracted from input
           string permutation,
           int outputLength//the length of output)
        {
             if (permutation.Length < outputLength)
             {
                 for (int i = 0; i < possibleArray.Length; i++)
                 {
                     var tempList = possibleArray.ToList();
                     tempList.RemoveAt(i);
                     MakePermutations(tempList.ToArray(), 
                          string.Concat(permutation, possibleArray[i]), outputLength);
                 }
             }
             else if (!result.Contains(permutation))
                result.Add(permutation);
        }
    

    and for Integer just change the caller method and MakePermutations() remains untouched:

        public static ICollection GetAllPermutations(int input, int outputLength)
        {
            result = new List();
            MakePermutations(input.ToString().ToCharArray(), string.Empty, outputLength);
            return result.Select(m => int.Parse(m)).ToList();
        }
    

    example 1: GetAllPermutations("abc",3); "abc" "acb" "bac" "bca" "cab" "cba"

    example 2: GetAllPermutations("abcd",2); "ab" "ac" "ad" "ba" "bc" "bd" "ca" "cb" "cd" "da" "db" "dc"

    example 3: GetAllPermutations(486,2); 48 46 84 86 64 68

提交回复
热议问题