递归算法

来源:互联网 发布:寂寞无人知 编辑:程序博客网 时间:2024/06/07 20:30

递归算法是一种常用的方法,其最大的特点就是在函数内部不断地调用自身函数,从而对问题进行求解
递归方法的举例如下:
下面是利用折线逼近曲线的算法示例。在该算法中,我们首先将曲线的首尾进行连接,然后求解曲线中到连线距离最大的点,作为折线的一个顶点。如果顶点到连线的距离大于设定的阈值,则重复上述的划分过程,直到折线的顶点到首尾连线的距离小于阈值为止。

void calMidIndex(int begin, int end, double threshold){    indexList.push_back(begin);    indexList.push_back(end);    int mid = computeMidIndex(begin, end);// 计算折线顶点索引    indexList.push_back(mid);    double dist = computeMidDist(begin, end);//计算顶点到begin-end连线的距离    if (dist >= threshold)    {        calMidIndex(begin, mid, threshold);// 使用递归方法进行求解        calMidIndex(mid, end, threshold);// 使用递归方法进行求解    }    else        return;}
0 0
原创粉丝点击