几种选择全排列实现的效率

统计几种选择全排列实现的效率,所谓选择全排列,如:在4个球之间选择2个球,其全排列数为 

代码如下:

#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <cmath>

using namespace std;
int cnt, cct, tot, n, k;
char a[25];
void test_1(int cur)
{
    if(cnt == k)
    {
        ++tot;
        return ;
    }
    else if(cur == n)
    {
        ++cct;
        return ;
    }
    ++cnt;
    test_1(cur + 1);
    --cnt;
    test_1(cur + 1);
}
void test_2(int cur)
{
    if(n - cur < k - cnt)
    // 剪枝,剩下的数的个数小于所需的1的个数时,不需要继续往下走了,直接返回
    {
        ++cct;
        return ;
    }
    if(cnt == k)
    {
        ++cct;
        return ;
    }
    else if(cur == n)
    {
        ++cct;
        return ;
    }
    ++cnt;
    test_2(cur + 1);
    --cnt;
    test_2(cur + 1);
}
void test_3(int cur)
{
    if(n - cur < k - cnt)
    {
        ++cct;
        return ;
    }
    if(cur == n)
    {
        ++cct;
        return ;
    }
    if(cnt <= k)
    {
        ++cnt;
        test_3(cur + 1);
        --cnt;
        test_3(cur + 1);
    }
    else
        test_3(cur + 1);
}
int main()
{
    n = 16; // 样本总个数
    k = 1;  // 选择出的个数
    printf("%d 个数的全排列的总个数为:%d.\n", n, (int)pow(2, n));

    tot = cnt = cct = 0;
    test_1(0);
    printf("%d 个里面选 %d个的全排列的总个数 %d.\n", n, k, tot);
    printf("一般回溯法的实际运行次数为:%10d, ", cct + tot);
    printf("效率 :%.4lf%%。\n", (double)tot / (double)(cct + tot) * 100);

    cnt = cct = 0;
    test_2(0);
    printf("剪枝优化后的实际运行次数为:%10d, ",  cct);
    printf("效率 :%.4lf%%.\n",  (double)tot / (double)cct * 100);

    cct = cnt = 0;
    test_3(0);
    printf("剪枝优化后的实际运行次数为:%10d, ",  cct);
    printf("效率 :%.4lf%%.\n",  (double)tot / (double)cct * 100);
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值