python全排列
1.所给数字列表无重复数字:[1,2,3] 回溯法:将每个位置的数字与第一个位置的数字互换,然后求得剩下的数字的全排列,结合递归算法就可以求出数列的全排列
class Solution(object): def permute(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ res = [] def pm(res, l, r, n, max): if n == max: res.append(l) for i in range(0, len(r)): pm(res, l+[r[i]], r[:i]+r[i+1:], n+1, max) pm(res, [], nums, 0, len(nums)) return res
2.所给列表有重复数字:[1,2,1]
先把列表排序,让重复数字相邻;利用vt列表,判断该数字是否有相同并且已经处理过,为真则跳过,否则继续进入递归。
class Solution(object): def permuteUnique(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ res = [] nums.sort() vt = [0]*len(nums) val = [] def pu(res, nums, val, vt): import pdb;pdb.set_trace() if len(val) == len(nums): res.append(val) for i in range(0, len(nums)): if i > 0 and nums[i] == nums[i-1] and vt[i - 1] == 0: continue if vt[i] == 0: vt[i] =1 pu(res, nums, val+[nums[i]], vt) vt[i] = 0 pu(res, nums, val, vt) return res if __name__ == "__main__": st = Solution() print st.permuteUnique([1,3,1])