题解 | #没有重复项数字的全排列#
没有重复项数字的全排列
http://www.nowcoder.com/practice/4bcf3081067a4d028f95acee3ddcd2b1
回溯的思想,当遍历到响应的元素后,注意还有一步测回的操作。
class Solution:
def permute(self , num: List[int]) -> List[List[int]]:
# write code here
if not num:
return None
num.sort()
res = []
self.backtrack(num, res, 0)
return res
def backtrack(self, num, res, index):
if index == len(num) - 1:
res.append(num)
else:
for i in range(index, len(num)):
temp = num[i]
num[i] = num[index]
num[index] = temp
self.backtrack(num, res, index + 1)
temp = num[i]
num[i] = num[index]
num[index] = temp