排列组合的实现

来源:互联网 发布:c语言的封装例子 编辑:程序博客网 时间:2024/06/06 13:59
排列的基本实现
#include<cstdio>#include<iostream>#include<cmath>#include<cstring>#include<algorithm>#include<cstdlib>using namespace std;int n = 0;void perm(int list[],int k,int m){    if(k>m)    {        for(int i=0;i<=m;i++)        {            cout<<list[i];        }        cout<<endl;        n++;    }    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(){    int list[]={1,2,3,4,5};    perm(list,0,4);    cout<<"所有的组合数目为:"<<n<<endl;    return 0;}

组合的基本实现

#include<cstdio>#include<iostream>#include<cmath>#include<cstring>#include<algorithm>#include<cstdlib>using namespace std;int combine(int a[], int n, int m){    m = m > n ? n : m;    int *order = new int[m+1];    for(int i=0; i<=m; i++)        order[i] = i-1;            // 注意这里order[0]=-1用来作为循环判断标识    int count = 0;    int k = m;    bool flag = true;           // 标志找到一个有效组合    while(order[0] == -1)    {        if(flag)                   // 输出符合要求的组合        {            for(int i=1; i<=m; i++)                cout << a[order[i]] << " ";            cout << endl;            count++;            flag = false;        }        order[k]++;                // 在当前位置选择新的数字        if(order[k] == n)          // 当前位置已无数字可选,回溯        {            order[k--] = 0;            continue;        }        if(k < m)                  // 更新当前位置的下一位置的数字        {            order[++k] = order[k-1];            continue;        }        if(k == m)            flag = true;    }    delete[] order;    return count;}int main(){    int a[100];    int n,m;    while(cin>>n>>m)    {        for(int i=0; i<n; i++)        {            cin>>a[i];        }        cout<<combine(a,n,m)<<endl;    }    return 0;}


原创粉丝点击