Problem Definition:
Given a collection of numbers, return all possible permutations.
For example,
[1,2,3]
have the following permutations:
[1,2,3]
, [1,3,2]
, [2,1,3]
, [2,3,1]
, [3,1,2]
, and [3,2,1]
.
Solution:
1)借用 Next Permutation 算法(线性),从最小的开始,找下一个......
1 # @param {integer[]} nums 2 # @return {integer[][]} 3 def permute(self, nums): 4 nums.sort() 5 pm=[nums[:]] 6 cnt=reduce(lambda x, y: x*y, range(1, len(nums)+1)) 7 for _ in range(cnt-1): 8 self.nextPermute(nums), 9 pm+=nums[:], 10 return pm 11 12 def nextPermute(self, nums): 13 n=len(nums) 14 if n<2: 15 return 16 i,j,pLeft,pRight=n-2,n-1,-1,n-1 17 while i>=0 and nums[i]>=nums[i+1]: 18 i-=1 19 if i>=0: 20 while j>i and nums[j]<=nums[i]: 21 j-=1 22 #must be j>i 23 nums[i],nums[j]=nums[j],nums[i] 24 pLeft=i+1 25 while pLeft<pRight: 26 nums[pLeft],nums[pRight]=nums[pRight],nums[pLeft] 27 pLeft+=1 28 pRight-=1
2)上面的解法,实现nextPerte函数有很多的细节要考虑。这题用回溯法比较好,idea比较直接,实现起来容易,性能也好。
1 # @param {integer[]} nums 2 # @return {integer[][]} 3 def permute(nums): 4 pms=[] 5 backTrack(nums, [], pms, len(nums)) 6 return pms 7 8 def backTrack(nums, localArr, pms, n): 9 if len(localArr)==n: 10 pms+=localArr[:], 11 else: 12 for i, e in enumerate(nums): 13 newNums=nums[:i]+nums[i+1:] 14 backTrack(nums[:i]+nums[i+1:], localArr+[e], pms, n)