dfs
遍历s串,对与s串的每个字母位,先不改变其大小写形式再继续向后搜索;搜索完毕后,再修改其大小写形式,再进行一遍搜索。
class Solution {
public:
int n;
vector<string> ans;
char get(char c){
if(c>='a'&&c<='z') c=c-'a'+'A';
else c=c-'A'+'a';
return c;
}
void dfs(int x,string s){
while(x<n&&s[x]>='0'&&s[x]<='9') x++;
if(x==n){
ans.push_back(s);
return;
}
dfs(x+1,s);
s[x]=get(s[x]);
dfs(x+1,s);
}
vector<string> letterCasePermutation(string s) {
n=s.size();
dfs(0,s);
return ans;
}
};
时间复杂度:O(n*2^n)。
空间复杂度:O(n*2^n),递归深度为n,而递归的状态有2^n个。