劍指offer面試題38. 字符串的排列(回溯)

題目描述

**輸入一個字符串,打印出該字符串中字符的所有排列。

你可以以任意順序返回這個字符串數組,但裏面不能有重複元素。**
在這裏插入圖片描述

思路

詳見鏈接

代碼

class Solution:
	def permutation(self,s:str)->List[str]:
		c, res = list(s),[]
		def dfs(x):
			if x == len(c) - 1
				res.append(''.join(c))
				return
			dic = set()
			for i in range(x,len(c)):
				if c[i] in dic:
					continue
				dic.add(c[i])
				c[i], c[x] = c[x], c[i]
				dfs(x+1)
				c[i], c[x] = c[x], c[i]
		dfs(0)
		return res
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章