算法/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结束递归

相关推荐
JieE21221 小时前
LeetCode 56. 合并区间|超清晰 JS 图解思路,面试高频区间题
javascript·算法·面试
Jack201 天前
HarmonyOS开发中错误处理策略:网络异常统一处理
算法
小小杨树1 天前
读懂色彩:拍照调色不再难
算法·计算机视觉·配色
JieE2122 天前
LeetCode 226. 翻转二叉树|JS 递归超详细拆解,二叉树入门经典题
javascript·算法
JieE2122 天前
LeetCode 104. 二叉树的最大深度|递归思路超详细拆解
javascript·算法
vivo互联网技术2 天前
CVPR 2026 | 全新强化学习框架 BeautyGRPO:重塑真实人像
算法·大模型·cvpr·影像
Darling噜啦啦2 天前
列表转树算法深度解析:从 Map 到 Reduce 的两种实现,面试高频考点
数据结构·算法·面试
clint4562 天前
C++进阶(1)——前景提要
c++
用户497863050732 天前
(一)小红的数组操作
算法·编程语言