题目
/*
* 给定字符串(合法字符只包括0,1,?),替换字符串中的通配符?为0或者1,生成所有可能的字符串。
* Input str = "1??0?101"
* Output:
* 10000101
* 10001101
* 10100101
* 10101101
* 11000101
* 11001101
* 11100101
* 11101101
*/
分析
算法1:非递归组合
- 计算?的个数,并记录其位置Index
- 求出组合数
- 将?所在的位置值,按位运算
算法2:DFS算法+回溯
代码
算法1:非递归组合
#include <iostream>
#include <map>
#include <vector>
#include <string>
#include <math.h>
using namespace std;
void Combine(string str, vector<string> *res)
{
string strR = str;
// counter ? , and tag the index...
map<int, int> mapIndex;
int nLen = str.length();
for (int i = 0; i < nLen; i++)
{
if (str.at(i) == '?')
mapIndex[i]='0';
}
int combinCount = pow(2,mapIndex.size());
for (int i = 0; i < combinCount; i++)
{
int nValue = i;
int qouteCount = 0;
for (map<int, int>::iterator it = mapIndex.begin(); it != mapIndex.end();it++)
{
int bitFlag = 1<<qouteCount;
qouteCount++;
// bit compute
strR[it->first] = (((nValue) & bitFlag) == (bitFlag)) ? '1': '0' ;
}
res->push_back(strR);
}
}
int main ()
{
string str= "1??0?101";
vector<string> res;
Combine(str, &res);
for (vector<string>::iterator iter =res.begin(); iter != res.end(); iter++ )
{
cout<<*iter<<endl;
}
return 0;
}
算法2:DFS算法+回溯
#include <iostream>
#include <map>
#include <vector>
#include <string>
#include <math.h>
using namespace std;
void helper(int index, string str, vector<string> *res)
{
if (index ==str.length())
{
res->push_back(str);
return;
}
if (str.at(index) == '?')
{
str[index] = '0';
helper(index + 1, str, res); // replace for 0
str[index] = '1';
helper(index + 1, str, res); // repalce for 1
str[index] = '?'; // repalce from self
}
else
{
helper(index + 1, str,res);
}
}
void DFS(string str, vector<string> *res)
{
helper(0, str, res);
}
int main ()
{
string str= "???";
vector<string> res;
DFS(str, &res);
// Combine(str, &res);
for (vector<string>::iterator iter =res.begin(); iter != res.end(); iter++ )
{
cout<<*iter<<endl;
}
return 0;
}