1. 题目:
无重复字符串的排列组合。编写一种方法,计算某字符串的所有排列组合,字符串每个字符均不相同。
示例1:
输入:S = "qwe"
输出:["qwe", "qew", "wqe", "weq", "ewq", "eqw"]
2. 代码:
DFS 模版+ used[]
class Solution:
def permutation(self, S: str) -> List[str]:
lens = len(S)
if lens == 0:
return []
elif lens ==1:
return S
def DFS(depth ,lens, res, path):
if depth == lens:
res.append(path[:])
return
for i in range(lens):
if used[i] == True:
continue
path = path+S[i]
used[i] = True
DFS(depth+1, lens, res, path)
path = path[:-1]
used[i] = False
res = []
path = ''
used = [False for _ in range(lens)]
DFS(0, lens, res, path)
return res
import itertools:
class Solution:
def permutation(self, S: str) -> List[str]:
import itertools
res = [''.join(i) for i in itertools.permutations(S)]
return res