杨辉三角的递归和非递归实现

杨辉三角描述:

  1. if m == 1: f(m,n) = n;
  2. if n == 1: f(m,n) = m;
  3. if m > 1, n >1: f(m,n) = f(m-1,n) + f(m,n -1);


递归算法实现:

unsigned int YHTriple(const unsigned int m, const unsigned int n)
{
	if (m == 1)
		return n;
	
	if (n == 1)
		return m;

	return YHTriple(m-1,n)+YHTriple(m,n-1); 

}

非递归算法实现:


#include<string>
unsigned  int YHTripleNotRecursion(const unsigned int m, const unsigned int n)
{
	std::vector<unsigned int> countTmp;
	for (int i = 1; i <= m; i++)
	{
		std::vector<unsigned int> tmp;
		for (int j = 1; j <= n; j++)
		{
			if (i == 1)
			{
				tmp.push_back(j);
				continue;
			}
			else if (j == 1)
			{
				tmp.push_back(i);
				continue;
			}
			tmp.push_back(tmp[j - 2] + countTmp[j-1]);
		}
		countTmp = tmp;
	}
	return countTmp[countTmp.size() -1];
}

    原文作者:杨辉三角问题
    原文地址: https://blog.csdn.net/lklzyy/article/details/25694167
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞