2017-10-07 117 views
0

我有一个方法返回给定字符串中3个元素的所有可能的组合。将三个嵌套for循环嵌入递归

void FindAllCombinationsBy3(string &str, int start) 
{ 
    for (int i = 0; i < str.length() - 2; i++) 
    { 
     for (int j = i + 1; j < str.length() - 1; j++) 
     { 
      for (int k = j + 1; k < str.length(); k++) 
      { 
      cout << str[i] << str[j] << str[k] << endl; 
      } 
     } 
    } 

    return; 
} 

它工作正常,并输出:abc abd abe abf acd ace acf ade。但我想写一个递归版本的方法,它将接收组合长度的参数n。所以不只是3,而是一个自定义的长度。它应该看起来像这样。但我在这种递归条件下迷失了。

void FindAllCombinationsByNValues(string &str, int start, int depth, int n) 
{ 
    if (depth++ >= n) 
    {  
     return; 
    } 

    for (int i = start; i < str.length() - n + depth; i++) 
    { 
     cout << str[i]; 
     FindAllCombinationsByNValues(str, start + 1, depth, n); 
    } 

    cout << endl; 
} 

我知道这被问了一百万次,但其他解决方案还没有帮助。

回答

1
void print_combinations(const std::string& s, unsigned n, unsigned j = 0, const std::string& a = "") { 
    if (n == 0) { 
    std::cout << a << std::endl; 
    } else { 
    for (auto i = j; i < s.length() - (n - 1); ++i) { 
     print_combinations(s, n - 1, i + 1, a + s[i]); 
    } 
    } 
} 

用法:

print_combinations("abcde", 3); 

输出:

abc 
abd 
abe 
acd 
ace 
ade 
bcd 
bce 
bde 
cde 
+0

有人密我在某些时候,但didn't积累人物像你一样。它有帮助 – earthQuake