排列组合算法之二: 01转换法_java改变后的c++改进版

http://blog.csdn.net/canguanxihu/article/details/46363375


排列组合算法之一: 01转换法_java改变后的c++版


class ZuheAssistArray
{
public:
    typedef std::vector<std::vector<int> > TZuheResult;

    ZuheAssistArray(int srcLen, int m)
    {
        int n = srcLen;      //C(n,m)

        // 生成辅助数组。首先初始化,将数组前m个元素置1,表示第一个组合为前m个数。
        std::vector<int> tempNum(srcLen, 0);
        for(int i = 0; i < m; ++i)
        {
            tempNum[i] = 1;
        }

        std::vector<int> oneof;
        m_zuheCalculation.push_back(createResult(tempNum, n, oneof));// 打印第一个默认组合

        // 然后从左到右扫描数组元素值的“10”组合,找到第一个“10”组合后将其变为“01”
        for (int i = 0; i < n - 1; i++)
        {
            if (tempNum[i] == 1 && tempNum[i + 1] == 0)
            {
                tempNum[i] = 0;
                tempNum[i + 1] = 1;
                std::sort(tempNum.begin(), tempNum.begin() + i, compare);
                m_zuheCalculation.push_back(createResult(tempNum, n, oneof));
                i = 0;
                continue;
            }
        }
        // 不判断是否为最后一个组合:计算结束时,不再有10组合
    }

    static bool compare(int a, int b){
        if(a > b){
            return true;
        }else{
            return false;
        }
    }

    //使用举例函数
    static void example()
    {
        int a[] = { 1, 2, 3, 4, 5 }; // 整数数组
        int m = 3; // 待取出组合的个数
        ZuheAssistArray zuhe(5, m);
        printZuheResult(a, zuhe.m_zuheCalculation);
    }

    // 打印组合结果
    static void printZuheResult(const int src[], TZuheResult zhr)
    {
        for (auto it = zhr.begin(); it != zhr.end(); it++)
        {
            for (auto itEle = it->begin(); itEle != it->end(); itEle++)
            {
                cout << src[*itEle] << " ";
            }
            cout << std::endl;
        }
    }
public:
    TZuheResult m_zuheCalculation;
private:
    // 根据辅助数组和原始数组生成 结果数组
    std::vector<int> & createResult(const std::vector<int>& assist,
        const int srcLen, std::vector<int> &dst)
    {
        dst.clear();
        for (int i = 0; i < srcLen; i++)
        {
            if (assist[i] == 1)
            {
                dst.push_back(i);
            }
        }
        return dst;
    }
};


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值