Listing all permutations of a string/integer

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

    Base/Revise on Pengyang answer

    And inspired from permutations-in-javascript

    The c# version FunctionalPermutations should be this

    static IEnumerable> FunctionalPermutations(IEnumerable elements, int length)
        {
            if (length < 2) return elements.Select(t => new T[] { t });
            /* Pengyang answser..
              return _recur_(list, length - 1).SelectMany(t => list.Where(e => !t.Contains(e)),(t1, t2) => t1.Concat(new T[] { t2 }));
            */
            return elements.SelectMany((element_i, i) => 
              FunctionalPermutations(elements.Take(i).Concat(elements.Skip(i + 1)), length - 1)
                .Select(sub_ei => new[] { element_i }.Concat(sub_ei)));
        }
    

提交回复
热议问题