【问题标题】:All permutations c++ with vector<int> and backtracking带有vector<int>和回溯的所有排列c ++
【发布时间】:2015-09-20 10:34:18
【问题描述】:

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

我的代码:

#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 但也许我错了有人可以告诉我是什么问题以及我该如何纠正它。

【问题讨论】:

标签: c++ vector permutation backtracking


【解决方案1】:

简单的方法是使用标准算法: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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-07
    • 1970-01-01
    • 2018-06-23
    • 2020-12-27
    • 1970-01-01
    • 2020-07-15
    相关资源
    最近更新 更多