博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
递归法
阅读量:6943 次
发布时间:2019-06-27

本文共 1711 字,大约阅读时间需要 5 分钟。

一:递归获得二叉树高度

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

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 
#include
#include
#include
#include
#include
#include
using namespace std;#define DEBUGset
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

 

转载于:https://www.cnblogs.com/jiayith/p/3923990.html

你可能感兴趣的文章
Flex Builder 3 下载与注册
查看>>
【存储方式】SharedPreference
查看>>
[转载]wp7
查看>>
WCF初见之HelloWorld
查看>>
无限循环小数怎么换成分数形式
查看>>
抄袭一点linux的经典资料
查看>>
ASP.net MVC: 一个开源的“留言系统”
查看>>
HTTP的请求头标签 If-Modified-Since
查看>>
阻塞和死锁问题整理一
查看>>
Android 时间日期Widget 开发详解
查看>>
[置顶] java 通过classloader加载类再通过classforname实例化
查看>>
Google Web Designer – 创建引人入胜的 HTML5 网站
查看>>
Qt5中的QtGui
查看>>
动态链接库(dll)简介(转)
查看>>
将某个组中的账户移动到新的OU下
查看>>
值得珍藏的资料--触摸技术的发展史(转)
查看>>
人声音乐声检测的小例子
查看>>
从头来之【图解针对虚拟机iOS开发环境搭建】 (转)
查看>>
常用命令
查看>>
bzoj 1798: [Ahoi2009]Seq 维护序列seq 线段树 区间乘法区间加法 区间求和
查看>>