题目
原题请参见1039. 字符组合
但是这次要求用set容器装好容器后再依次输出
代码模板
/***************************************************************/
/* */
/* DON'T MODIFY main function ANYWAY! */
/* */
/***************************************************************/
#include <iostream>
#include <string>
#include <set>
using namespace std;
//********** Specification of Combination **********
set<string> Combination(string s);
/* PreCondition:
s is a string with distinct characters in ascending order
PostCondition:
return combination of string s
*/
/***************************************************************/
int main(int argc, char** argv)
{
string s;
cout << "Enter a string: ";
cin >> s;
cout << endl << "Result: "<< endl;
bool first{true};
//********** Combination is called here **************
for (const auto& x: Combination(s))
//**************************************************
{
if (first) first=false;
else cout << " ";
cout << x;
}
cout << endl;
return 0;
}
思路
dfs在1039中有提及,这里由于需要用到set容器
题目提示用递归来写。。。学术不精。没想出来一个参数怎么弄递归
所以用迭代,直接二进制枚举符合的所有情况,然后一股脑塞进set让他自己排序
代码
/***************************************************************/
/* */
/* DON'T MODIFY main function ANYWAY! */
/* */
/***************************************************************/
#include <iostream>
#include <string>
#include <set>
using namespace std;
set<string> SET;
long long power(long long base, long long n)//处理二进制
{
if(n == 0) return 1;
long long temp = base;
for(int i = 1; i < n; i++)
{
base *= temp;
}
return base;
}
//********** Specification of Combination **********
set<string> Combination(string s)
{
int size = power(2,s.length());
while(size--)
{
int bin = size;
string a = "";
int loc = s.length() - 1;
while(bin)
{
if(bin & 1)
{
a.insert(0,1,s[loc]);
}
loc--;
bin /= 2;
}
SET.insert(a);
}
return SET;
};
/* PreCondition:
s is a string with distinct characters in ascending order
PostCondition:
return combination of string s
*/
/***************************************************************/
int main(int argc, char** argv)
{
string s;
cout << "Enter a string: ";
cin >> s;
cout << endl << "Result: "<< endl;
bool first{true};
//********** Combination is called here **************
for (const auto& x: Combination(s))
//**************************************************
{
if (first) first=false;
else cout << " ";
cout << x;
}
cout << endl;
return 0;
}