写一个程序,打印出以下的序列。
(a),(b),(c),(d),(e)........(z)
(a,b),(a,c),(a,d),(a,e)......(a,z),(b,c),(b,d).....(b,z),(c,d).....(y,z)
(a,b,c),(a,b,d)....(a,b,z),(a,c,d)....(x,y,z)
....
(a),(b),(c),(d),(e)........(z)
(a,b),(a,c),(a,d),(a,e)......(a,z),(b,c),(b,d).....(b,z),(c,d).....(y,z)
(a,b,c),(a,b,d)....(a,b,z),(a,c,d)....(x,y,z)
....
(a,b,c,d,.....x,y,z)
这道题是从luciferisnotsatan的博客上看到的, 这里是他的实现:网易笔试的一道题
下面是我的实现:
#include <iostream>
using namespace std;
void show()
{
char const character[] =
{
'a', 'b', 'c', 'd', 'e', 'f', 'g',
'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't',
'u', 'v', 'w', 'x', 'y', 'z'
};
int length = sizeof(character) / sizeof(character[0]);
int index[sizeof(character) / sizeof(character[0])] = { 0 };
for (int set_size = 1; set_size <= length; ++set_size) {
for (int i = 0; i < set_size; ++i) {
index[i] = i;
}
int end = length - (set_size - 1);
while (index[0] < end) {
cout << "(" << character[index[0]];
for (int i = 1; i < set_size; ++i) {
cout << ',' << character[index[i]];
}
cout << ")";
if (index[0] < end - 1) {
cout << ",";
}
++index[set_size - 1];
int max = length;
int check = set_size - 1;
while (check > 0 && index[check] == max) {
--check;
++index[check];
--max;
}
for (int i = check + 1; i < set_size; ++i) {
index[i] = index[i - 1] + 1;
}
}
cout << endl;
}
}
int main()
{
show();
return 0;
}
我这里实现手法与我之前的文章: 试题:集合的划分问题 相同