zoukankan      html  css  js  c++  java
  • 递归法

    一:递归获得二叉树高度

      因为树本身就是递归定义,创建也可以递归创建,所以高度不也可以递归获得嘛?如下:

    int getHeight(Node* pNode)
    {
        if (pNode)
        {
            左树高度 = getHeight(pNode->lChild)
            右树高度 = getHeight(pNode->rChild)
            return 左右树高度较大者 + 1
        }
        else
        {
            return 0;
        }
    }

      关于树的问题很多都和递归思想有关。




    二:递归得出所有可能

      华为OJ上一道题:http://career-oj.huawei.com/exam/ShowSolution?method=SolutionApp&id=2091;

      这种题目显然是必须弄出所有可能情况,而且用循环的方式不好做,并且每一层处理都是类似的,很容易想到递归的思想。

    #include <iostream>
    #include <string>
    #include <cstdlib>
    #include <cmath>
    #include <cctype>
    #include <set>
    #include <map>
    
    using namespace std;
    #define DEBUG
    
    set<int> s;            //装不同结果的集合
    
    void handleRes(const int& n, const int* pWeight, const int* pNum, int* pCalc,  const int thisIndex)
    {
        //对这种重量的砝码,取不同的个数
        for (int i = 0; i <= pNum[thisIndex]; i++)            //注意:这里可以等于!!!
        {
            //先取
            pCalc[thisIndex] = i;
            
            //边界判断
            //最后一列,那么到了递归的结尾,直接计算即可
            if (n - 1 == thisIndex)
            {
                //计算这种情况下总体的重量
                int thisWeight = 0;
                for (int j = 0; j < n; j++)
                    thisWeight += pWeight[j] * pCalc[j];
    
                s.insert(thisWeight);        //反正set会处理重复的
            }
            else
            {
                //递归下一种情况,注意在递归处理下一种情况之前,后面的应该重视没有处理过
                for (int j = thisIndex + 1; j < n; j++)
                    pCalc[j] = 0;
    
                handleRes(n, pWeight, pNum, pCalc, thisIndex + 1);
            }
    
    
        }
    }
    
    int main(void)
    {
        //获取有关输入
        int n;
        cin >> n;
        
        int* pWeight = new int[n];
        int* pNum = new int[n];
        int* pCalc = new int[n];
        if (!pWeight || !pNum || !pCalc)
            return 1;
    
        for (int i = 0; i < n; i++)
            cin >> pWeight[i];
    
        for (int i = 0; i < n; i++)
        {
            cin >> pNum[i];
            pCalc[i] = 0;        //放各种可能的数组先置空,表明都是放0个
        }
    
        //开始处理,从下标为0的砝码开始处理
        handleRes(n, pWeight, pNum, pCalc, 0);
    
        cout << s.size();
    
    #ifdef DEBUG
        while (true)
            cin.get();
    #endif
    }
    View Code
  • 相关阅读:
    Ceph 之RGW Cache
    Ceph 之RGW Pub-Sub Module
    Ceph 之RGW Data Layout
    RocksDB 之Write Ahead Log(WAL)
    Ceph 之 Background on http frontends
    Ceph 之Multisite 下的bucket reshard
    Ceph之PG数调整
    Ceph之对象存储网关RADOS Gateway(RGW)
    window mysql重启、忘记密码等操作
    selenium处理HTML5视频播放未能自动播放解决办法
  • 原文地址:https://www.cnblogs.com/jiayith/p/3923990.html
Copyright © 2011-2022 走看看