C++刷leetcode(784. 字母大小写全排列)【深度优先搜索】
本帖最后由 糖逗 于 2020-5-8 17:58 编辑题目描述:
给定一个字符串S,通过将字符串S中的每个字母转变大小写,我们可以获得一个新的字符串。返回所有可能得到的字符串集合。
示例:
输入: S = "a1b2"
输出: ["a1b2", "a1B2", "A1b2", "A1B2"]
输入: S = "3z4"
输出: ["3z4", "3Z4"]
输入: S = "12345"
输出: ["12345"]
注意:
S 的长度不超过12。
S 仅由数字和字母组成。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/letter-case-permutation
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
#include <iostream>
#include<string>
#include <vector>
using namespace std;
void dfs(string S, vector<string>& res, string temp, int start){
if(temp.size() == S.size()) res.push_back(temp);
if(S >= '0' && S <= '9'){
temp += S;
dfs(S, res, temp, start+1);
temp.erase(temp.end()-1);
}
int store = {0, 32};
if((S >='A' && S <='Z') || (S >='a' && S <='z'))
for(int i = 0; i < 2; i++){
int temp2 = islower(S) ? -1:1;
temp += char(S +store * temp2);
dfs(S, res, temp, start+1);
temp.erase(temp.end()-1);
}
}
vector<string> letterCasePermutation(string S) {
vector<string> res;
dfs(S, res, "", 0);
return res;
}
int main(void){
string input;
cin >> input;
vector<string> res = letterCasePermutation(input);
for(int i = 0; i < res.size(); i++){
for(int j = 0; j < res.size(); j++){
cout << res << " ";
}
cout << endl;
}
return 0;
}
注意事项:
1.解题思路如图1。
页:
[1]