算法课程笔记——全排列

要最小

ventor用endl

递归方式


#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;

}

使用系统函数


#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;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

HineMusk

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

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

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

打赏作者

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

抵扣说明:

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

余额充值