Listing all permutations of a string/integer

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

    Lists permutations of a string. Avoids duplication when characters are repeated:

    using System;
    using System.Collections;
    
    class Permutation{
      static IEnumerable Permutations(string word){
        if (word == null || word.Length <= 1) {
          yield return word;
          yield break;
        }
    
        char firstChar = word[0];
        foreach( string subPermute in Permutations (word.Substring (1)) ) {
          int indexOfFirstChar = subPermute.IndexOf (firstChar);
          if (indexOfFirstChar == -1) indexOfFirstChar = subPermute.Length;
    
          for( int index = 0; index <= indexOfFirstChar; index++ )
            yield return subPermute.Insert (index, new string (firstChar, 1));
        }
      }
    
      static void Main(){
        foreach( var permutation in Permutations ("aab") )
          Console.WriteLine (permutation);
      }
    }
    

提交回复
热议问题