n个字符的全排列

n个字符的全排列

通过递归的方法进行排列 输出

#include "stdafx.h"
#include <iostream>
using namespace std;
//函数声明
template <typename T>
inline void Swap(T& a, T& b);
template <typename T>
void Perm(T list[], int k, int m);

int main()
{
    int m;
    cin >> m;
    char list[20];
    int a=0;

    //字符数组的读取
    cin >> list[a];
    a++;
    while (cin.get() != '\n'&&a < m) {
        cin >> list[a];
        a++;
    }
    //调用递归的函数 进行排列
    Perm(list, 0, m - 1);

    return 0;
}
//核心函数 *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
template <typename T>
void Perm(T list[], int k, int m)
{
    int i;
    if (k == m) {
        for (i = 0; i <= m; i++) {
            cout << list[i];
            if (i == m) {
                cout << endl;
            }

        }
    }
    else {
        for (i = k; i <= m; i++) {
            Swap(list[k], list[i]);
            Perm(list, k + 1, m);
            Swap(list[k], list[i]);
        }
    }

}
//Swap函数 顾名思义 交换数组元素的位置
template <typename T>
inline void Swap(T& a, T& b) {
    T temp = a; a = b; b = temp;
}

这里写图片描述

猜你喜欢

转载自blog.csdn.net/weixin_43036613/article/details/82633250