[LeetCode] 46. Permutations_Medium tag: DFS, backtracking
2019-05-24 09:27 Johnson_强生仔仔 阅读(263) 评论(0) 编辑 收藏 举报
Given a collection of distinct integers, return all possible permutations.
Example:
Input: [1,2,3] Output: [ [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1] ]
这个题目就是用for loop取nums的值,然后再recursive求去掉num之后的nums的permutation,再将两者组合 起来。
时间复杂度 = 方案总数 * 构造方案所需时间
O( n ! * n)
Code
class solution: def permutations(self, nums): ans = [] def helper(ans, temp, nums): if not nums: ans.append(temp)
for i in range(len(nums)): helper(ans, temp + [nums[i]], nums[:i] + nums[i + 1:]) helper(ans, [], nums) return ans
利用python的itertools
class Solution: def permutaions(self, nums): return itertools.permutations(nums)