记录刷题的过程。牛客和力扣中都有相关题目,这里以牛客的题目描述为主。该系列默认采用python语言。
1、问题描述:
输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。
2、数据结构:
字符串
3、题解:
可以和567 字符串的排列一起做
上图选自https://leetcode-cn.com/problems/zi-fu-chuan-de-pai-lie-lcof/solution/mian-shi-ti-38-zi-fu-chuan-de-pai-lie-hui-su-fa-by/
-*- coding:utf-8 -*-
class Solution:
def Permutation(self, ss):
# write code here
c,res = list(ss),[]
#dfs
def dfs(depth):
#返回条件
if depth == len(c) -1:
res.append(''.join(c))
return
dic = set()
for i in range(depth,len(c)):
if c[i] in dic:
continue
dic.add(c[i])
c[i],c[depth] = c[depth],c[i]
dfs(depth + 1)
c[i],c[depth] = c[depth],c[i]
dfs(0)
return res
或者:
class Solution:
def Permutation(self, ss):
# write code here
if not ss: return []
s = list(sorted(ss))
res = []
def helper(s, tmp):
if not s: res.append(''.join(tmp))
for i, char in enumerate(s):
if i > 0 and s[i] == s[i - 1]:
continue
helper(s[:i] + s[i + 1:], tmp + [char])
helper(ss, [])
return res
另外有数组的全排列:
class Solution:
def permuteUnique(self, nums: List[int]) -> List[List[int]]:
res=[]
nums.sort()
def helper(nums,temp):
if not nums:
res.append(temp)
for i in range(len(nums)):
if i>0 and nums[i]==nums[i-1]:
continue
helper(nums[:i]+nums[i+1:],temp+[nums[i]])
helper(nums,[])
return res