数据结构与算法(C语言版)__排列组合

来源:互联网 发布:图片热点 js 边框 编辑:程序博客网 时间:2024/04/30 03:17

排列组合(Permutation)
使用递归的方法实现排列组合
图中可以看到
图中可以看到a后面跟着bc的排列组合,b后面跟着ac的排列组合,c后面跟着ab的排列组合,自然而然可以想到使用递归的方法。
这里写图片描述

#include<iostream>using namespace std;int c1 = 0;//查看进入迭代int c2 = 0;//查看返回迭代void Permutations(char *p, const int k, const int m){    cout<<"c1 = "<<++c1<<endl;    if (k == m){        for (int i = 0; i <= m; i++){            cout << p[i];        }        cout << endl;    }    else{        for (int i = k; i <= m; i++){                swap(p[k], p[i]);                Permutations(p, k + 1, m);                cout <<"c2 = "<< ++c2 << endl;                swap(p[k], p[i]);            }    }    //a开头的,后面跟着bc的所有排列    //swap(p[0], p[0]);    //Permutations(p, 1, 2);    //b开头的,后面跟着ac的所有排列    //swap(p[0], p[1]);    //Permutations(p, 1, 2);    //swap(p[0], p[1]);    //c开头的,后面跟着ab的所有排列    //swap(p[0], p[2]);    //Permutations(p, 1, 2);    //swap(p[0], p[2]);}int main(){    char s[] = "abc";    Permutations(s, 0, 2);    system("pause");    return 0;}

使用下面的代码可以详细看到递归的过程

#include<iostream>using namespace std;int c1 = 0;int c2 = 0;void show(char *p, int m){    for (int i = 0; i <= m; i++){        cout << p[i];    }    cout << endl;}void Permutations(char *p, const int k, const int m){    cout << "c1 = " << ++c1 << endl;    if (k == m){        for (int i = 0; i <= m; i++){            cout << p[i];        }        cout << endl;    }    else{        for (int i = k; i <= m; i++){            cout << "递归前,交换前:";            show(p, m);            swap(p[k], p[i]);            cout << "递归前,交换后:";            show(p, m);            Permutations(p, k + 1, m);            cout << "c2 = " << ++c2 << endl;            cout << "递归后,交换前:";            show(p, m);            swap(p[k], p[i]);            cout << "递归后,交换后:";            show(p, m);        }    }    //a开头的,后面跟着bc的所有排列    //swap(p[0], p[0]);    //Permutations(p, 1, 2);    //b开头的,后面跟着ac的所有排列    //swap(p[0], p[1]);    //Permutations(p, 1, 2);    //swap(p[0], p[1]);    //c开头的,后面跟着ab的所有排列    //swap(p[0], p[2]);    //Permutations(p, 1, 2);    //swap(p[0], p[2]);}int main(){    char s[] = "abc";    Permutations(s, 0, 2);    system("pause");    return 0;}

总结:递归是非常好用的方法,仔细思考问题的细节,然后写出递归的方法。

0 0
原创粉丝点击