Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 置换:返回第k个置换_Python_Algorithm_Python 2.7_Permutation - Fatal编程技术网

Python 置换:返回第k个置换

Python 置换:返回第k个置换,python,algorithm,python-2.7,permutation,Python,Algorithm,Python 2.7,Permutation,例如,我知道对于这个问题有一个时间复杂度的解决方案 我只是好奇为什么我在O(2^n)中的天真方法在Python中不起作用 算法: 我只是递归地查找排列,当添加kth元素时,我返回它。但是,我得到的返回结果是None。我不确定为什么我的函数返回None class Solution(object): # Time complexity O(2 ^ n) def getPermutation(self, n, k): char_list = map(str, ran

例如,我知道对于这个问题有一个时间复杂度的解决方案

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

算法: 我只是递归地查找排列,当添加
k
th元素时,我返回它。但是,我得到的返回结果是
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()

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

因为您正在将
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

看一看。在
\u getPermutation\u helper()
的多个路径中没有返回任何内容。如果遵循其中一个路径,则返回值为
None
,这很可能就是您正在打印的内容。FWIW,
r不是None
优先于
r!=无
,因为测试对象标识比比较对象的值便宜。@pm2r如果是这样,我已将其更改为
r不是无
。谢谢