Source: http://zhedahht.blog.163.com/blog/static/2541117420114172812217/ question: enter a string to output all combinations of Characters in the string. For example, if ABC is input, its combination includes a, B, c, AB, AC, BC, and ABC.
Analysis: In this series of blogs titled "string Arrangement", we have discussed in detail how to use recursive methods to find the string arrangement. Likewise, you can use recursive methods to obtain a string combination.
Suppose we want to evaluate the combination of M characters in a string with a length of N. We will first scan the first character of the string from the beginning. For the first character, we have two options: one is to put this character in the combination, and then we need to select the -1 character from the remaining n-1 characters; instead of putting this character in the combination, We need to select M characters in the remaining n-1 characters. Both options are easily implemented using recursion. The following is a reference code for this idea:
#include<iostream>#include<vector>using namespace std;void Combination(char* string, int number, vector<char>& result){ if(number == 0) { vector<char>::iterator iter = result.begin(); for(; iter < result.end(); ++ iter) printf("%c", *iter); printf("\n"); return; } if(*string == '\0') return; result.push_back(*string); Combination(string + 1, number - 1, result); result.pop_back(); Combination(string + 1, number, result);}void combination(char* string){ if(string == NULL) return; int length = strlen(string); vector<char> result; for(int i = 1; i <= length; ++ i) { Combination(string, i, result); }} int main(){ char *str ="abcd"; combination(str); getchar(); return 0;}
Because the combination can be a combination of 1 character and 2 character ...... Until the combination of n characters, so in the Void Function
Combination (char * string), we need a for loop. In addition, we use a vector to store the characters that we choose to put into the combination.