permutation in c#

前端 未结 5 2106
无人共我
无人共我 2021-01-13 05:16

Is it possible to generate all permutations of a collection in c#?

char[] inputSet = { \'A\',\'B\',\'C\' };
Permutations permutations = new Permu         


        
5条回答
  •  情话喂你
    2021-01-13 05:30

    A simple implementation using recursion

        static void Main(string[] args)
        {
            char[] inputSet = { 'A', 'B', 'C' };
            var permutations = GetPermutations(new string(inputSet));
            foreach (var p in permutations)
            {
                Console.WriteLine(String.Format("{{{0} {1} {2}}}", p[0], p[1], p[2]));
            }
        }
    
        public static List GetPermutations(string str)
        {
            List result = new List();
    
            if (str == null)
                return null;
    
            if (str.Length == 0)
            {
                result.Add("");
                return result;
            }
    
            char c = str.ElementAt(0);
            var perms = GetPermutations(str.Substring(1));
    
            foreach (var word in perms)
            {
                for (int i = 0; i <= word.Length; i++)
                {
                    result.Add(word.Substring(0, i) + c + word.Substring(i));
                }
            }
    
            return result;
        }
    

提交回复
热议问题