Listing all permutations of a string/integer

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

    It's just two lines of code if LINQ is allowed to use. Please see my answer here.

    EDIT

    Here is my generic function which can return all the permutations (not combinations) from a list of T:

    static IEnumerable>
        GetPermutations(IEnumerable list, int length)
    {
        if (length == 1) return list.Select(t => new T[] { t });
    
        return GetPermutations(list, length - 1)
            .SelectMany(t => list.Where(e => !t.Contains(e)),
                (t1, t2) => t1.Concat(new T[] { t2 }));
    }
    

    Example:

    IEnumerable> result =
        GetPermutations(Enumerable.Range(1, 3), 3);
    

    Output - a list of integer-lists:

    {1,2,3} {1,3,2} {2,1,3} {2,3,1} {3,1,2} {3,2,1}
    

    As this function uses LINQ so it requires .net 3.5 or higher.

提交回复
热议问题