Listing all permutations of a string/integer

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

    Here's a high level example I wrote which illustrates the human language explanation Peter gave:

        public List FindPermutations(string input)
        {
            if (input.Length == 1)
                return new List { input };
            var perms = new List();
            foreach (var c in input)
            {
                var others = input.Remove(input.IndexOf(c), 1);
                perms.AddRange(FindPermutations(others).Select(perm => c + perm));
            }
            return perms;
        }
    

提交回复
热议问题