打印字符串C ++`的所有组合

时间:2015-01-21 22:59:45

标签: string combinations permutation puzzle

问题:给定字符串 x 排序,然后打印所有组合。 (在hackerrank / interviewbit / geeksforgeeks等编码网站上找到)

这是一个例子......

输入:字符串x =“BAC”

输出: [ABC,AB,AC,BC,A,B,C]

当前工作解决方案:(仅适用于x.length()= 3)

的情况
void printCombinations(string q){
    stack<char> c;
    stack<char> c2;
    sort(q.begin(), q.end());
    for(int i = 0; i<q.size(); i++){
        cout<<q[i];
        c.push(q[i]);
    }
    cout<<endl;

    for(int i = 0; i<q.size(); i++){
      char t = c.top();
      cout<<t<<endl;
      for(int j=0; j<c.size(); j++){
        c.pop();
        c2.push(c.top());
        cout<< t << c.top() <<endl;
      }
      c.pop();
      c = c2;
    }
}

3 个答案:

答案 0 :(得分:1)

我不确定为什么在您的问题中发布的代码仅适用于三个字符的字符串,但是它存在一些问题(例如,您不需要访问堆栈)。

可以通过将string转换为char数组并迭代来解决此问题。 可以找到类似于您所使用的代码here,同一页面也给出了解决方案的名称(backtracking)和一个很好的小图,解释了它如何使用字符串{{1}例如:

http://www.geeksforgeeks.org/wp-content/uploads/NewPermutation.gif

然而,此代码并不能满足您的需求,而是开箱即用,但是对代码进行了少量修改:

代码中的某个地方有一个小错误,它会使结果产生奇怪的字符输出,但是 会打印出所有组合。 调查此内容并在我有解决方案时更新代码。

ABC

答案 1 :(得分:1)

    void printCombinations(string q){
    cout<<"We are now printing out all the combinations of "<<q<<endl;
    sort(q.begin(), q.end());
    bitset<10> b;
    int count =0;
    for(int i=0; i<pow(2,q.size()); ++i){
        for(int x=0;x<10;x++){
            if(b[x] == 1){
                cout<<q[x]; 
            }
        }
        count++;
        cout<<endl;
        for( int j=0; j<10;j++){
            if(b[j]==1){
                b[j].flip();
            }
            else{
                b[j].flip();
                break;
            }
        }
    }   
    cout<<"There are "<<count<<" combinations"<<endl;
}

以上是上述问题的一种解决方案。

答案 2 :(得分:0)

打印给定字符串的所有组合的另一种解决方案。我在代码中给出了注释,解释了每一行的作用。

void combination(int index, string instr, string outstr)
{
    for (auto i = index; i < instr.length(); i++)
    {
        outstr += instr.at(i);             // 1: Append a char
        cout<<outstr << " ";               // 2: Print the current combination
        combination(i + 1, instr, outstr); // 3: Recursive call at level i + 1
        outstr.erase(outstr.length() - 1, 1); // 4: Balance/Remove the char added at step 1
    }
}

int main()
{
    combination(0, "ABC","");
    return 0;
}

输出:

A AB ABC AC B BC C