51nod 全排列

参考了网上大神的判重方法, 还有用c++函数next_permutation(a,a+n), 字符数组a是数组开始全排列的状态,随后字典序排列输出,n为长度。如果需要输出全部的排列,需要对字符数组a排序。 

全排列的实质是将前面的数与后面不和已经使用过并且和当前相同的字符交换。这句话交换是全排列,但是出现aab这样的需要去重,就需要刚刚说过的后面这句绕口的话。

计蒜客 全排列

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int N=1e3;
char str[N], buf[N];//buffer
int vis[N], total, len;
void arrange(int num) {
    if (num == len){
        printf("%s\n", buf);
        total++;
        return;
    }
	for (int i = 0; i < len; ++i) {
        if (!vis[i]) {
            int j;
            for (j = i + 1; j < len; ++j) {
                if (vis[j]&&str[j]==str[i]) {
                    break;
                }
            }
            if (j == len) {
                vis[i] = 1;
                buf[num] = str[i];
                arrange(num + 1);
                vis[i] = 0;
            }
        }
    }
}
int main() {
    while (~scanf("%s",str)) {
        len = strlen(str);
        sort(str, str + len);
        total = 0;
        buf[len] = '\0';
        arrange(0);
        printf("Total %d\n", total);
    }
    return 0;
}

51nod 全排列

#include<iostream>

#include<cstdio>
#include <cstring>
#include <algorithm>
#define LL long long
using namespace std;
const int N = 50;
bool vis[N];
char str[N], ans[N];
int len;
void dfs(int cur)
{
    if(cur==len)
    {
        printf("%s\n", ans);
        return ;
    }


    for(int i = 0; i<len;i++)
    {
        if(!vis[i])
        {
            vis[i] = 1;
            ans[cur] = str[i];
            dfs(cur+1);
            vis[i]=0;
            while(i<len&&str[i]==str[i+1])i++;
        }
    }
}
int main()
{
    while(~scanf("%s", str))
    {
        len = strlen(str);
        sort(str, str+len);
        dfs(0);
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值