小编Nic*_*Law的帖子

获取所有不重复的组合

给出 C++ 中没有重复的字符串的所有可能组合。输入示例:“123”,输出组合为:

 1,12,123,13,2,23,3.
Run Code Online (Sandbox Code Playgroud)

重复的示例为“12”==“21”或“123”==“213”。

假设一个字符不会被多次使用。我也不认为递归是强制性的。

这里有一个 php 答案。(获取所有可能的组合而不重复)。

我考虑过某种形式的结果树,但不确定如何用递归来实现。

我的答案(包括重复项)如下:

#include <string>
#include <iostream>
using namespace std;

void get( string str, string res ) {

   cout << res << endl;

   for( int i = 0; i < str.length(); i++ )
      get( string(str).erase(i,1), res + str[i] );
}

int main( int argc, char **argv) {
   string str = "123";
   get( str, "" );
   return 0;
}
Run Code Online (Sandbox Code Playgroud)

这是一个面试问题,没有重复的问题让我很困惑。预先感谢您的任何帮助。

c++ recursion combinations

1
推荐指数
1
解决办法
3583
查看次数

标签 统计

c++ ×1

combinations ×1

recursion ×1