有重复元素的排列问题

来源:互联网 发布:内向工作知乎 编辑:程序博客网 时间:2024/05/17 23:07
#include "iostream"#include "algorithm"#include "fstream"using namespace std;int ans = 0;//判断list数组中第i个元素是否在前面元素list[k...i-1]中出现过//如果出现过,返回0, 否则返回1int ok(char list[], int k, int i){    if(i>k)        for(int j=k; j<i; j++)            if(list[j] == list[i])                return 0;    return 1;}//list[0,n],k为层数void perm(char list[], int k, int n){    if(k==n)    {        ans++;        for(int i=0; i<=n; i++)            cout << list[i];        cout << endl;    }    for(int i=k; i<=n; i++)    {        if(ok(list, k, i)) //先判断list数组中第i个元素是否在前面元素list[k...i-1]中出现过        {                  //若出现过,这次以i元素打头的全排列跳过。            swap(list[k], list[i]);            perm(list, k+1, n);            swap(list[k], list[i]);         }    }}int main(){    ifstream fin("perm.txt");    int n;    fin >> n;    cout << "字符个数:" << n;    char *a = new char[n];    cout << "\n字符串为:";    for(int i=0; i<n; i++)    {        fin >> a[i];        cout << a[i];    }    cout << "\n全排列为:\n";    perm(a, 0, n-1);    cout << "个数为:" << ans << endl;    fin.close();    return 0;} 

这里写图片描述

0 0
原创粉丝点击