Listing all permutations of a string/integer

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

        //Generic C# Method
                private static List GetPerms(T[] input, int startIndex = 0)
                {
                    var perms = new List();
    
                    var l = input.Length - 1;
    
                    if (l == startIndex)
                        perms.Add(input);
                    else
                    {
    
                        for (int i = startIndex; i <= l; i++)
                        {
                            var copy = input.ToArray(); //make copy
    
                            var temp = copy[startIndex];
    
                            copy[startIndex] = copy[i];
                            copy[i] = temp;
    
                            perms.AddRange(GetPerms(copy, startIndex + 1));
    
                        }
                    }
    
                    return perms;
                }
    
                //usages
                char[] charArray = new char[] { 'A', 'B', 'C' };
                var charPerms = GetPerms(charArray);
    
    
                string[] stringArray = new string[] { "Orange", "Mango", "Apple" };
                var stringPerms = GetPerms(stringArray);
    
    
                int[] intArray = new int[] { 1, 2, 3 };
                var intPerms = GetPerms(intArray);
    

提交回复
热议问题