Listing all permutations of a string/integer

后端 未结 29 2050
没有蜡笔的小新
没有蜡笔的小新 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条回答
  •  闹比i
    闹比i (楼主)
    2020-11-22 01:40

    Building on @Peter's solution, here's a version that declares a simple LINQ-style Permutations() extension method that works on any IEnumerable.

    Usage (on string characters example):

    foreach (var permutation in "abc".Permutations())
    {
        Console.WriteLine(string.Join(", ", permutation));
    }
    

    Outputs:

    a, b, c
    a, c, b
    b, a, c
    b, c, a
    c, b, a
    c, a, b
    

    Or on any other collection type:

    foreach (var permutation in (new[] { "Apples", "Oranges", "Pears"}).Permutations())
    {
        Console.WriteLine(string.Join(", ", permutation));
    }
    

    Outputs:

    Apples, Oranges, Pears
    Apples, Pears, Oranges
    Oranges, Apples, Pears
    Oranges, Pears, Apples
    Pears, Oranges, Apples
    Pears, Apples, Oranges
    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    
    public static class PermutationExtension
    {
        public static IEnumerable Permutations(this IEnumerable source)
        {
            var sourceArray = source.ToArray();
            var results = new List();
            Permute(sourceArray, 0, sourceArray.Length - 1, results);
            return results;
        }
    
        private static void Swap(ref T a, ref T b)
        {
            T tmp = a;
            a = b;
            b = tmp;
        }
    
        private static void Permute(T[] elements, int recursionDepth, int maxDepth, ICollection results)
        {
            if (recursionDepth == maxDepth)
            {
                results.Add(elements.ToArray());
                return;
            }
    
            for (var i = recursionDepth; i <= maxDepth; i++)
            {
                Swap(ref elements[recursionDepth], ref elements[i]);
                Permute(elements, recursionDepth + 1, maxDepth, results);
                Swap(ref elements[recursionDepth], ref elements[i]);
            }
        }
    }
    

提交回复
热议问题