Permutation: return kth permutation

I know that for this problem there is a solution O(n), here .

I'm just wondering why my naive approach in O(2^n)not working in Python.

Algorithm:

I just find the permutations recursively, and when the kth element is added , I return it. However, I get a return result None. I am not sure why it Nonereturns with my function.

class Solution(object):

    # Time complexity O(2 ^ n)
    def getPermutation(self, n, k):
        char_list = map(str, range(1, n + 1)) #convert to strin
        used = [False] * len(char_list)
        result = []
        kthArray = self._getPermutation_helper(result, char_list, used, [], k)
        print kthArray #kthArray is always None

    def _getPermutation_helper(self, result, char_list, used, cur,  k):
        if len(char_list) == len(cur):
            result.append(cur + [])
            print len(result)
            print cur
        if len(result) == k:
            print "cur in kth is {0}".format(cur)
            return cur #cur is printed correctly but not returned
        for i in range(len(char_list)):
            if not used[i]:
                cur.append(char_list[i])
                used[i] = True
                self._getPermutation_helper(result, char_list, used, cur, k)
                # back track
                used[i] = False
                cur.remove(char_list[i])
def main():
    pgm = Solution()
    pgm.getPermutation(3, 6)

if __name__ == "__main__":
    main()

Why is the correct value not returned?

+4
source share
1 answer

cur , .

. :

    for i in range(len(char_list)):
        if not used[i]:
            cur.append(char_list[i])
            used[i] = True

            # Here we do a recursive call, which might find the answer we're looking for.
            # So we save its return value and, if it not None, we return it.
            r = self._getPermutation_helper(result, char_list, used, cur, k)
            if r is not None:
                return r
+3

Source: https://habr.com/ru/post/1606585/


All Articles