【问题标题】:Print Unique Permutation in C++在 C++ 中打印唯一排列
【发布时间】:2015-02-04 02:38:44
【问题描述】:

我正在寻找仅打印的唯一排列。该函数应将一个字符串作为输入并按字典(字母)顺序打印出该字符串的唯一排列(不重复)。

这是我到目前为止所拥有的,但是当我运行时它给了我一个错误。我认为我在 printPermutations 中的参数与主函数不匹配,但我无法更改主函数,因为它是用来测试代码的。

void printPermutations(string word, int currentIndex, int wordSize){

if(currentIndex == wordSize){
    cout << word << endl;
    return;
}
else{
    for (int j = currentIndex; j = wordSize; j++){
        swap(word[currentIndex], word[j]);
        printPermutations(word, currentIndex +1, wordSize);
        swap(word[currentIndex], word[j]);
    }
}

}

int main(int argc, char* argv[]){
string word = "abcd";
printPermutations(argv[1]);
return 0;
}

【问题讨论】:

  • 如果您正在寻找如何打印所有排列,这需要 3 行 C++ 代码来完成。
  • 我正在寻找仅打印的唯一排列。应该将一个字符串作为输入并以字典(字母)顺序打印出该字符串的唯一排列(不重复)的函数。
  • 对不起,这是我第一次来这里。

标签: c++


【解决方案1】:

正如已经相当尖锐地确定你正在寻找的是next_permutation你可以做这样的事情:

void printPermutations(const string& word){
    sort(word.begin(), word.end());

    cout << "1. " << word << endl;

    for(int i = 2; next_permutation(word.begin(), word.end()); ++i){
        cout << i << ". " << word << endl;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-10
    • 2018-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多