■ 题目描述
考古问题,假设以前的石碑被打碎成了很多块,每块上面都有一个或若干个字符,请你写个程序来把之前石碑上文字可能的组合全部写出来,按升序进行排列。
示例1 输入输出示例仅供调试,后台判题数据一般不包含示例
输入
3
a b c
输出
abc
acb
bac
bca
cab
cba
示例2 输入输出示例仅供调试,后台判题数据一般不包含示例
输入
3
a b a
输出
aab
aba
baa
class Solution:
def permute(self, words):
res = [] # 存放组合结果
size = len(words)
def backtrack(combination, words):
# combination目前已经产生的组合,nums为剩下的数组
# 递归出口
# 递归的结束一定 要有return
if len(combination) == size:
res.append(combination)
return # 注意
for i in range(len(words)):
backtrack(combination + [words[i]], words[:i] + words[i + 1:]) # 递归回溯
backtrack([], words)
return res
if __name__ == '__main__':
num = int(input())
words = input().split()
solution = Solution()
for i in solution.permute(words):
print(''.join(i))