c++ - 所有排列 C++ 与 vector <int> 和回溯

标签 c++ vector permutation backtracking

我正在尝试生成 vector 的所有排列来训练回溯技术,但我的代码不适用于所有 vector (适用于 vector 大小)

我的代码:

#include <bits/stdc++.h>

using namespace std;

void permutations(int s,vector<int> v){
    if(s>=v.size())
        return;
    if( v.size()==0)
        cout<<endl;
    cout<<v[s]<<" ";
    vector<int> k = v;

    k.erase(k.begin()+s);

    for(int i =0;i<k.size();i++)
        return permutations(i,k);

}

int main(int argc, char const *argv[])
{
    vector<int> v = {1,2,3};
    for(int i =0;i<v.size();i++){
        permutations(i,v);
        cout<<endl;
    }

    return 0;
}

我认为是因为当我的递归函数 find return 时,它们破坏了 for 但也许我错了,有人可以告诉我问题是什么以及我该如何纠正它。

最佳答案

简单的方法是使用标准算法:std::next_permutation

void print(const std::vector<int>& v)
{
    for (int e : v) {
        std::cout << " " << e;
    }
    std::cout << std::endl;
}

int main()
{
    std::vector<int> v = {1,2,3};
    // vector should be sorted at the beginning.

    do {
        print(v);
    } while (std::next_permutation(v.begin(), v.end()));
}

Live Demo

关于c++ - 所有排列 C++ 与 vector <int> 和回溯,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32678349/

相关文章:

c++ - exe文件图标变化。取自 SHELL32.dll 的图标

c++ - CGAL新手问题: Which segments intersect?

c++ - 对于 gtest,如何模拟名称相同但类型不同的方法

arrays - Delphi中向量/数组的梯度(nabla)

c++ - C++ 中 vector 的内部工作?

java - Java ArrayList 中元素的 k 排列

c++ - MFC GUI 自定义控件 : how to draw cursor updates in response to mouse moves?

c++ - Cout vector 地址

python - 在 Python 中组合单词(排列?)

erlang - 如何有效地存储一大组排列?