Listing all permutations of a string/integer

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

    First of all, sets have permutations, not strings or integers, so I'll just assume you mean "the set of characters in a string."

    Note that a set of size n has n! n-permutations.

    The following pseudocode (from Wikipedia), called with k = 1...n! will give all the permutations:

    function permutation(k, s) {
        for j = 2 to length(s) {
            swap s[(k mod j) + 1] with s[j]; // note that our array is indexed starting at 1
            k := k / j; // integer division cuts off the remainder
        }
        return s;
    }
    

    Here's the equivalent Python code (for 0-based array indexes):

    def permutation(k, s):
        r = s[:]
        for j in range(2, len(s)+1):
            r[j-1], r[k%j] = r[k%j], r[j-1]
            k = k/j+1
        return r
    

提交回复
热议问题