全排列

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了全排列相关的知识,希望对你有一定的参考价值。

1、问题描述:一串字母/数字的组合,进行不同的排列顺序,最终全部打印出来。

  分析:的用到递归的思想。

2、代码实现

考虑到通用性,模板的使用,所以用C++实现:

#include<iostream>
using namespace std;

template<class Type>  //交换2个数的函数
void swap_(Type &a, Type &b){
    Type tmp = a;
    a = b;
    b = tmp;
}

template<class Type>
void Perm(Type list[], int k, int m){
    if(k == m){  //结束条件
        for(int i = 0; i <= m; i++){
            cout<<list[i];
        }
        cout<<endl;
    }else{
        for(int i = k; i <= m; i++){
            swap_(list[k], list[i]);
            Perm(list, k+1, m); //递归下一个数
            swap_(list[k], list[i]);
        }
    }
}

int main(void){
    int ar[] = {1,2,3};
    int n = sizeof(ar) / sizeof(int);
    Perm(ar, 0, n-1); //传ar,下标0,最后一个数字的下标(n-1)

    return 0;
}

结果如下

技术分享



本文出自 “11586096” 博客,请务必保留此出处http://11596096.blog.51cto.com/11586096/1859001

以上是关于全排列的主要内容,如果未能解决你的问题,请参考以下文章