杨辉三角描述:
- if m == 1: f(m,n) = n;
- if n == 1: f(m,n) = m;
- 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];
}