Listing all permutations of a string/integer

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

    class Program
    {
        public static void Main(string[] args)
        {
            Permutation("abc");
        }
    
        static void Permutation(string rest, string prefix = "")
        {
            if (string.IsNullOrEmpty(rest)) Console.WriteLine(prefix);
    
            // Each letter has a chance to be permutated
            for (int i = 0; i < rest.Length; i++)
            {                
                Permutation(rest.Remove(i, 1), prefix + rest[i]);
            }
        }
    }
    

提交回复
热议问题