[英]Finding Kth lexicographic permutation when repetition is allowed using Factoradic system
[英]Permutation: return the kth permutation
我知道有一個O(n)
對這個問題的時間復雜度的解決方案, 這里的例子。
我只是好奇為什么我在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()
為什么沒有返回正確的值?
因為你正在返回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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.