c++全排列---递归与next_permutation函数

今天,在《算法笔记》里面看了全排列!字节就总结一下,方便以后复习使用;

在这里插入图片描述

  • 全排列的递归写法;
    这里插入一个视频,看了视频就好理解了。

[算法教程] 全排列

(ps:我个人觉得他的写法有问题,但是他的思想是与下面递归代码符合)

#include <iostream>
using namespace std;

void Perm(int start, int end, int a[]){
    //得到全排列的一种情况,输出结果
    if (start == end){
        for (int i = 0; i < end; i++)
            cout << a[i];
        cout << endl;
        return;
    }
    for (int i = start; i < end; i++){
        swap(a[start], a[i]);      //交换
        Perm(start + 1, end, a);   //分解为子问题a[start+1,...,end-1]的全排列
        swap(a[i], a[start]);      //回溯
    }
}
int main() {
    int i, n, a[10];
    while (cin >> n, n) {
        for (i = 0; i < n; i++)
        {
            a[i] = i + 1;
        }
        Perm(0, n, a);
    }
    return 0;
}
  • 全排列的调用函数next_permutation函数;

先看一个代码:

#include <cstdio>
#include <iostream>
#include <cmath>
#include <cstring>
#include <algorithm>
using namespace std;
int a[200];
int main()
{
    int i,j,n;
    scanf("%d",&n);
    for (i=0;i<n;i++)
        a[i]=i+1;
    do{
        for(i=0;i<n;i++)
        {
            printf("%d",a[i]);
            if (i<n-1)
                cout<<" ";
        }
        cout<<endl;
    }while (next_permutation(a,a+n));
    return 0;
}

是不是很懵,没事,下面就有详细的介绍:
next_permutation的函数声明:#include
bool next_permutation( iterator start, iterator end);
next_permutation函数的返回值是布尔类型,在STL中还有perv_permutation()函数

以ABC为例

#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main()
{
    string str;
    cin >> str;
    sort(str.begin(),str.end());
    while (next_permutation(str.begin(), str.end()))
        cout << str << endl;
    return 0;
}

// 输出结果:
G:\clion\qifei\cmake-build-debug\qifei.exe
ABC
ACB
BAC
BCA
CAB
CBA

Process finished with exit code 0

next_permutation()函数功能是输出所有比当前排列大的排列,顺序是从小到大。
而prev_permutation()函数功能是输出所有比当前排列小的排列,顺序是从大到小。

next_permutation函数的原理如下:
在当前序列中,从尾端向前寻找两个相邻元素,前一个记为i,后一个记为t,并且满足i < t。然后再从尾端
寻找另一个元素
j,如果满足
i < *j,即将第i个元素与第j个元素对调,并将第t个元素之后(包括t)的所有元
素颠倒排序,即求出下一个序列了。

prev_permutation()函数示例:

#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main()
{
    string str;
    cin >> str;
    while (prev_permutation(str.begin(), str.end()))
        cout << str << endl;
    return 0;
}

//  输出结果:
G:\clion\qifei\cmake-build-debug\qifei.exe
CBA
CAB
BCA
BAC
ACB
ABC

Process finished with exit code 0

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Liknana

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值