Listing all permutations of a string/integer

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

    This is my solution which it is easy for me to understand

    class ClassicPermutationProblem
    {
        ClassicPermutationProblem() { }
    
        private static void PopulatePosition(List> finalList, List list, List temp, int position)
        {
             foreach (T element in list)
             {
                 List currentTemp = temp.ToList();
                 if (!currentTemp.Contains(element))
                    currentTemp.Add(element);
                 else
                    continue;
    
                 if (position == list.Count)
                    finalList.Add(currentTemp);
                 else
                    PopulatePosition(finalList, list, currentTemp, position + 1);
            }
        }
    
        public static List> GetPermutations(List list)
        {
            List> results = new List>();
            PopulatePosition(results, list, new List(), 1);
            return results;
         }
    }
    
    static void Main(string[] args)
    {
        List> results = ClassicPermutationProblem.GetPermutations(new List() { 1, 2, 3 });
    }
    

提交回复
热议问题