Listing all permutations of a string/integer

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

        /// 
        /// Print All the Permutations.
        /// 
        /// input string
        /// length of the string
        /// output string
        private void PrintAllPermutations(string inputStr, int strLength,string outputStr, int NumberOfChars)
        {
            //Means you have completed a permutation.
            if (outputStr.Length == NumberOfChars)
            {
                Console.WriteLine(outputStr);                
                return;
            }
    
            //For loop is used to print permutations starting with every character. first print all the permutations starting with a,then b, etc.
            for(int i=0 ; i< strLength; i++)
            {
                // Recursive call : for a string abc = a + perm(bc). b+ perm(ac) etc.
                PrintAllPermutations(inputStr.Remove(i, 1), strLength - 1, outputStr + inputStr.Substring(i, 1), 4);
            }
        }        
    

提交回复
热议问题