ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

c++实现全排列的三种方式

2022-04-18 15:34:06  阅读:134  来源: 互联网

标签:index 排列 string int c++ 三种 str include size


递归方式

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
const int MAXN = 10;

bool visit[MAXN];//判断某个元素是否被访问过
char sequence[MAXN];//存放找到的全排列

void GetPermutation(string str, int index){
    // 找到结果并打印
    if (index == str.size()) {
        // 打印结果
        for (int i = 0; i < str.size(); ++i) {
            putchar(sequence[i]);
        }
        printf("\n");
    }
    for (int i = 0; i < str.size(); ++i) {
        if (visit[i]) {//被访问过就跳过
            continue;
        } else {
            visit[i] = true;
            sequence[index] = str[i];
            //接着查找下一位
            GetPermutation(str, index + 1);
            visit[i] = false;
        }
    }
}
int main(){
    string str;
    while (cin >> str) {
        sort(str.begin(), str.end());// 输入的字符串排序,保证以字典序输出
        GetPermutation(str, 0);
        printf("\n");
    }
    return 0;
}

非递归方式

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;

//非递归方式
//依次给出该排列的下一个排列
bool GetNextPermutation(string &str){
    int n = str.size();
    int index = n - 2;// 指向倒数第二个字符的下标
    //如果当前字符比后面的字符大就前移
    while (index >= 0 && str[index] >= str[index + 1]) {
        index--;
    }
    // 已经是字典序最大了
    if (index < 0) {
        return false;
    }
    for (int i = n - 1; i > index; --i) {
        // 找到第一个大于index的字符,然后交换
        if (str[i] > str[index]) {
            swap(str[index], str[i]);
            break;
        }
    }
    reverse(str.begin() + index + 1, str.end());
    return true;
}
int main(){
    string str;
    while (cin >> str) {
        sort(str.begin(), str.end());
        do {
            cout << str << endl;
        } while (GetNextPermutation(str));
        cout << endl;
    }

    return 0;
}

使用系统函数

next_permutation()和非递归方式求全排列的用法一样,是计算当前序列的下一个序列,该函数位于algorithm头文件中。

它有三个参数:

  • 序列的首地址
  • 序列的尾地址
  • 比较函数(可选),默认是字典序排列
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;

int main(){
    string str;
    while (cin >> str) {
        sort(str.begin(), str.end());
        do {
            cout << str << endl;
        } while (next_permutation(str.begin(), str.end()));
        cout << endl;
    }

    return 0;
}

标签:index,排列,string,int,c++,三种,str,include,size
来源: https://www.cnblogs.com/lxy0/p/16159832.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有