所有排列 c++ 与向量<int>和回溯

All permutations c++ with vector<int> and backtracking

本文关键字:int gt 回溯 lt c++ 向量 排列      更新时间:2023-10-16

我正在尝试生成一个矢量的所有排列来训练回溯技术,但我的代码不适用于所有矢量(工作到矢量大小)

my code:

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

我想是因为当我的递归函数找到返回时,他们打破了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()));
}

现场演示