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

相关推荐
lcj25111 分钟前
深入理解指针(4):qsort 函数 & 通过冒泡排序实现
c语言·数据结构·算法
Sylvia-girl1 分钟前
线程池~~
java·开发语言
fie88892 分钟前
基于MATLAB的转子动力学建模与仿真实现(含碰摩、不平衡激励)
开发语言·算法·matlab
lly2024065 分钟前
C# 变量作用域
开发语言
唐梓航-求职中9 分钟前
编程大师-技术-算法-leetcode-1472. 设计浏览器历史记录
算法·leetcode
时艰.9 分钟前
java性能调优 — 高并发缓存一致性
java·开发语言·缓存
MSTcheng.10 分钟前
【C++】C++智能指针
开发语言·c++·智能指针
无小道12 分钟前
Qt——网络编程
开发语言·qt
_OP_CHEN12 分钟前
【算法基础篇】(五十八)线性代数之高斯消元法从原理到实战:手撕模板 + 洛谷真题全解
线性代数·算法·蓝桥杯·c/c++·线性方程组·acm/icpc·高斯消元法
wazmlp00188736914 分钟前
第五次python作业
服务器·开发语言·python