排列:返回第k个排列

2024-04-26 12:06:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道这个问题有一个O(n)时间复杂性的解决方案,例如here。在

我只是好奇为什么我在O(2^n)中的天真方法在Python中不起作用。在

算法:

我只是递归地查找置换,当添加第k个元素时,我将返回它。但是我得到的返回结果是None。我不知道为什么函数返回None。在

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()

为什么没有返回正确的值?在


Tags: selfhelpernonelenifisdefresult
1条回答
网友
1楼 · 发布于 2024-04-26 12:06:38

因为您将返回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's not None, we return it.
            r = self._getPermutation_helper(result, char_list, used, cur, k)
            if r is not None:
                return r

相关问题 更多 >