给定一个 没有重复 数字的序列,返回其所有可能的全排列。
class Solution(object):
def __init__(self):
self.number_status = list()
self.total_list = list()
def permutations(self,number_list,temp=[]):
if len(temp)==len(number_list):
self.total_list.append(temp.copy())
return
for i in range(len(number_list)):
if i >= len(self.number_status):
self.number_status.append(False)
if not self.number_status[i]:
temp.append(number_list[i])
self.number_status[i] = True
self.permutations(number_list,temp)
temp.pop(-1)
self.number_status[i] = False
return self.total_list
x=Solution()
total_list = x.permutations([1,2,3])
print(total_list)
output:
[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
给定一个有重复 数字的序列,返回其所有可能的全排列且不重复
class Solution(object):
def __init__(self):
self.number_status = list()
self.total_list = list()
def permutations2(self,number_list,temp=[]):
# 如果结果长度和输入长度相等,则添加进结果集
if len(temp)==len(number_list):
self.total_list.append(temp.copy())
return
number_list.sort()
for i in range(len(number_list)):
if i >= len(self.number_status): #将数字状态列表补齐至数值列表的长度
self.number_status.append(False)
# 如果该元素已经被使用过,则继续遍历
if not self.number_status[i]:
# 下一个重复值只有在前一个重复值被使用的情况下才可以使用
if (i>0 and number_list[i-1] == number_list[i] and not self.number_status[i-1]): continue
temp.append(number_list[i])
self.number_status[i] = True
self.permutations2(number_list,temp)
temp.pop(-1)
self.number_status[i] = False
return self.total_list
x=Solution()
total_list = x.permutations2([1,2,2,2])
print(total_list)
output:
[[1, 2, 2, 2], [2, 1, 2, 2], [2, 2, 1, 2], [2, 2, 2, 1]]
网友评论