1. 题⽬链接:784.字⺟⼤⼩写全排列
2. 题⽬描述:
3. 解法:
算法思路:
只需要对英⽂字⺟进⾏处理,处理每个元素时存在三种情况:
1. 不进⾏处理;
2. 若当前字⺟是英⽂字⺟并且是⼤写,将其修改为⼩写;
3. 若当前字⺟是英⽂字⺟并且是⼩写,将其修改为⼤写。
递归函数设计:void dfs(int step)
参数:step(当前需要处理的位置);
返回值:⽆;
函数作⽤:查找所有可能的字符串集合,并将其记录在答案列表。
从前往后按序进⾏递归,递归流程如下:
1. 递归结束条件:当前需要处理的元素下标越界,表⽰处理完毕,记录当前状态并返回;
2. 对当前元素不进⾏任何处理,直接递归下⼀位元素;
3. 判断当前元素是否为⼩写字⺟,若是,将其修改为⼤写字⺟并递归下⼀个元素,递归结束时撤销修 改操作;
4. 判断当前元素是否为⼤写字⺟,若是,将其修改为⼩写字⺟并递归下⼀个元素,递归结束时撤销修 改操作;
C++算法代码:
class Solution
{
public:
vector<string>answer; //总答案
string key; //单个选项
void dfs(string s,int t)
{
//出口
if(key.size()==s.size())
{
answer.push_back(key);
return;
}
//数字不改变
key.push_back(s[t]);
dfs(s,t+1);
key.pop_back();
//字母改变
if(islower(s[t]))
{
key.push_back(toupper(s[t]));
dfs(s,t+1);
key.pop_back();
}
if(isupper(s[t]))
{
key.push_back(tolower(s[t]));
dfs(s,t+1);
key.pop_back();
}
}
vector<string> letterCasePermutation(string s)
{
dfs(s,0);
return answer;
}
};
class Solution
{
string path;
vector<string> ret;
public:
vector<string> letterCasePermutation(string s)
{
dfs(s, 0);
return ret;
}
void dfs(string& s, int pos)
{
if (pos == s.length())
{
ret.push_back(path);
return;
}
char ch = s[pos];
// 不改变
path.push_back(ch);
dfs(s, pos + 1);
path.pop_back(); // 恢复现场
// 改变
if (ch < '0' || ch > '9')
{
char tmp = change(ch);
path.push_back(tmp);
dfs(s, pos + 1);
path.pop_back(); // 恢复现场
}
}
char change(char ch)
{
if (ch >= 'a' && ch <= 'z') ch -= 32;
else ch += 32;
return ch;
}
};
Java算法代码:
class Solution
{
StringBuffer path;
List<String> ret;
public List<String> letterCasePermutation(String s)
{
path = new StringBuffer();
ret = new ArrayList<>();
dfs(s, 0);
return ret;
}
public void dfs(String s, int pos)
{
if (pos == s.length())
{
ret.add(path.toString());
return;
}
char ch = s.charAt(pos);
// 不改变
path.append(ch);
dfs(s, pos + 1);
path.deleteCharAt(path.length() - 1); // 恢复现场
// 改变
if (ch < '0' || ch > '9')
{
char tmp = change(ch);
path.append(tmp);
dfs(s, pos + 1);
path.deleteCharAt(path.length() - 1); // 恢复现场
}
}
public char change(char ch)
{
if (ch >= 'a' && ch <= 'z') return ch -= 32;
else return ch += 32;
}
}