【问题标题】:wrap three nested for loops into recursion将三个嵌套的 for 循环包装成递归
【发布时间】:2017-10-07 18:24:40
【问题描述】:

我有一个方法可以返回给定字符串中 3 个元素的所有可能组合。

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;
}

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

【问题讨论】:

    标签: c++ recursion combinations


    【解决方案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
    

    【讨论】:

    • 我在某个时候很接近,但没有像你那样积累字符。它有帮助
    猜你喜欢
    • 1970-01-01
    • 2013-09-25
    • 1970-01-01
    • 2018-08-12
    • 1970-01-01
    • 2019-04-14
    • 1970-01-01
    • 2020-03-09
    • 1970-01-01
    相关资源
    最近更新 更多