// traverse letters from the first one to the last one.
// combination[ ] is used to save the result of each combination.
// layer indicates the number of letters in the combination, also it tells you
// the position of the newly visited letter in combination[ ]
// layer increases by one in each recursion
Algorithm:
C(string, combination, length, layer, start)
for i = start to length
// put the traversed letters into combination[]
combination[layer] = string[i]
print the combination
if (start+1 <= length) C(string, combination, length, layer+1, i+1)
Code:
#include#include using namespace std; int sum =0; char str[] = "1234"; int length; char *combination; void DoCombine(char in[], char combination[], int length, int layer, int start) { int i; for( i = start; i < length; i++) { combination[layer] = in[i]; combination[layer+1] = 0; cout << combination << endl; if(i < length - 1) DoCombine(in, combination, length, layer+1, i+1); } } int main() { length = strlen(str); combination = new char[length+1]; DoCombine(str, combination, length, 0, 0); delete [] combination; return 0; }
No comments:
Post a Comment