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):
def getPermutation(self, n, k):
char_list = map(str, range(1, n + 1))
used = [False] * len(char_list)
result = []
kthArray = self._getPermutation_helper(result, char_list, used, [], k)
print kthArray
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
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)
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?
source
share