题目描述:
https://leetcode-cn.com/problems/letter-case-permutation/
思路:将字符串的转化看作一个二叉树的遍历(如下图),但要注意一点,在数字节点上,不能进行分支,否则会产生重复的情况。
#include<cstdio>
#include<iostream>
#include<vector>
#include<string.h>
#include<stdlib.h>
using namespace std;
/*
s:传入的字符串
flag:标志数组,判断字串第i位上是数字还是字母
list:结果集
times:正在处理的字串的位数
*/
void Permutation(string s,int flag[],vector<string>& list,int times)
{
if(times==s.length())
{
list.push_back(s);
return;
}
else
{
string str1 = s;
str1[times] = tolower(str1[times]);
Permutation(str1,flag,list,times+1);
//防止在数字处之后出现重复情况
if(flag[times] == 0)
{
string str2 = s;
str2[times] = toupper(str2[times]);
Permutation(str2,flag,list,times+1);
}
}
}
vector<string> letterCasePermutation(string s)
{
vector<string> result;
//字符串长度
int length = s.length();
//标志数组,判断字串第i位上是数字还是字母
int flag[12];
memset(flag,0,sizeof(int)*12);
for(int i=0;i<length;++i)
if(s[i]<=57&&s[i]>=48)
flag[i] = 1;
Permutation(s,flag,result,0);
return result;
}
int main(){
string s = "a1b2c3";
vector<string> result = letterCasePermutation(s);
for(int i=0;i<result.size();++i)
printf("%s\n",result[i].c_str());
return 0;
}