[小算法]从M个不同字符中任取N个字符的所有组合
2011-08-30 15:08 Kevin Pan 阅读(485) 评论(0) 编辑 收藏 举报非递归算法
#include "stdafx.h"
#include <iostream>
using namespace std;
void GetCombination(char * chars, int n);
int main()
{
GetCombination("abcdefg", 3);
system("pause");
return 0;
}
void GetCombination(char * chars, int n)
{
int index[10];
int strLength = strlen(chars);
for (int i = 0; i < n;i++)
{
index[i] = i;
}
bool end = false;
while(!end)
{
for(int i = 0; i < n; i++)
{
cout << chars[index[i]];
}
cout << endl;
for(int i = n - 1; i >= -1; i--)
{
if(i < 0)
{
end = true;
break;
}
if(index[i] < strLength - n + i)//strLength - 1 - ( n - 1 -i)
{
index[i]++;
for(int j = i + 1; j < n ;j++)
{
index[j] = index[j - 1] + 1;
}
break;
}
}
}
}
#include <iostream>
using namespace std;
void GetCombination(char * chars, int n);
int main()
{
GetCombination("abcdefg", 3);
system("pause");
return 0;
}
void GetCombination(char * chars, int n)
{
int index[10];
int strLength = strlen(chars);
for (int i = 0; i < n;i++)
{
index[i] = i;
}
bool end = false;
while(!end)
{
for(int i = 0; i < n; i++)
{
cout << chars[index[i]];
}
cout << endl;
for(int i = n - 1; i >= -1; i--)
{
if(i < 0)
{
end = true;
break;
}
if(index[i] < strLength - n + i)//strLength - 1 - ( n - 1 -i)
{
index[i]++;
for(int j = i + 1; j < n ;j++)
{
index[j] = index[j - 1] + 1;
}
break;
}
}
}
}