题目
描述
输入一个长度为 n 字符串,打印出该字符串中字符的所有排列,你可以以任意顺序返回这个字符串数组。
例如输入字符串ABC,则输出由字符A,B,C所能排列出来的所有字符串ABC,ACB,BAC,BCA,CBA和CAB。
数据范围:n<10
要求:空间复杂度 O(n!),时间复杂度 O(n!)
输入描述:
输入一个字符串,长度不超过10,字符只包括大小写字母。
思路
采用深度优先搜索的思想来解决全排列的问题,深度优先搜索有两种状态,一种是当前状态,一种是可选状态。不断更新当前状态和可选状态。
如abc
[] [abc]
[a][bc]
[b][c]
[c][b]
[b][ac]
[a][c]
[c][a]
[c][ab]
[a][b]
[b][a]
代码
python代码:
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param str string字符串
# @return string字符串一维数组
#
class Solution:
res = []
def Permutation(self , str: str) -> List[str]:
# write code here
curr = ""
store = str
self.dfs(curr, store)
return self.res
def dfs(self, curr, store):
if not len(store):
self.res.append(curr)
return
for i in range(len(store)):
if(i>0 and store[i]==store[i-1]):
continue
self.dfs(curr+store[i], store[0:i]+store[i+1:])
c++代码
class Solution {
public:
vector<string> res;
int n;
vector<string> Permutation(string str) {
this->n = str.size();
// sort(str.begin(), str.end());
string curr = "";
string store = str;
dfs(curr, store);
return res;
}
void dfs(string curr, string store){
//curr表示当前状态,store表示可选状态
//1、是否满足条件,返回结果
//2、判断终止条件
//3、继续搜索
if(store.empty()){
return res.push_back(curr);
}
for(int i=0; i<store.size(); i++){
//去重
if(store[i]==store[i-1]){
continue;
}
int len = store.size();
dfs(curr+store[i], store.substr(0,i)+store.substr(i+1,len));
}
}
};