leetcode46:
给定一个没有重复数字的序列,返回其所有可能的全排列。
class Solution:
def backtrack(self, res, temp, nums):
if len(temp) == len(nums):
res.append(temp[:])
else:
for i in nums:
if i in temp:
continue
else:
temp.append(i)
self.backtrack(res, temp, nums)
temp.pop()
def permute(self, nums):
res = []
temp = []
self.backtrack(res, temp, nums)
return res
leetcode47:
给定一个可包含重复数字的序列,返回所有不重复的全排列。
class Solution(object):
def permuteUnique(self, nums):
res = []
temp = []
remain = nums[:]
self.cantsubnum(temp, remain, res)
return res
def cantsubnum(self, temp, remain, res):
if len(remain) == 0:
res.append(temp)
old_nums = [] # 本层循环是否被访问过的数组
for i in range(len(remain)):
if remain[i] in old_nums:
continue
self.cantsubnum(temp+[remain[i]], remain[0:i]+remain[i+1:], res)
old_nums.append(remain[i])