算法/C++ STL排列&手动可选择排列

cpp 复制代码
#include<bits/stdc++.h>
using namespace std;
int main()
{
    string s;
    cin >> s;
    sort(s.begin(), s.end());
    do {
        cout << s << endl;
    } while (next_permutation(s.begin(), s.end()));
    cout << endl;
    sort(s.begin(), s.end(),greater<char>());
    do {
        cout << s << endl;
    } while (prev_permutation(s.begin(), s.end()));
    return 0;
}

简单明了,全靠 next/prev_permutation 函数,这是一个非常好用的排序函数,但无法进行剪枝的操作,即在明知当前排列已经错误时无法停止,会导致超时。

这是就需要我们手写一个排列函数

cpp 复制代码
#include<bits/stdc++.h>
using namespace std;

vector<int> a={1,2,3,4,5,6,7,8,9,10};
bool vis[20];
int b[20];

void dfs(int s,int t,vector<int>&a2){
    if(s == t){
        for(int i = 0; i < t; ++i) cout << b[i] << " ";
        cout << endl;
        return;
    }
//剪枝操作
    for(int i = 0; i < t; i++){
        if(!vis[i]){
            vis[i] = true;
            b[s] = a2[i];
            dfs(s + 1,t,a2);
            vis[i] = false;
        }
    }
    return;
}
int main(){
    int start,end;
    cin>>start>>end;
     vector<int> a2(a.begin() + start - 1, a.begin() + end);
    dfs(0,end-start+1,a2);
    return 0;
}

这里没有具体的例子大致是满足一个具体的条件后return结束递归

相关推荐
泯仲3 分钟前
Ragent项目7种设计模式深度解析:从源码看设计模式落地实践
java·算法·设计模式·agent
dulu~dulu7 分钟前
算法---寻找和为K的子数组
笔记·python·算法·leetcode
moonsea020317 分钟前
【无标题】
算法
春日见19 分钟前
E2E自驾规控30讲:导论
开发语言·驱动开发·git·matlab·计算机外设
wangchunting20 分钟前
Jvm-垃圾收集器
java·开发语言·jvm
沐知全栈开发32 分钟前
PHP Math: 精通PHP中的数学函数与应用
开发语言
佑白雪乐38 分钟前
<ACM进度212题>[2026-3-1,2026-3-26]
算法·leetcode
穿条秋裤到处跑42 分钟前
每日一道leetcode(2026.03.26):等和矩阵分割 II
算法·leetcode·矩阵
吴声子夜歌43 分钟前
JavaScript——call()、apply()和bind()
开发语言·前端·javascript
平凡灵感码头1 小时前
C语言 printf 数据打印格式速查表
c语言·开发语言·算法