计算Tribonaci队列, 规则是T(n) = T(n - 1) + T(n - 2) + T(n -3),其中T(0) = T(1) = 1,T(2) = 2。
/** Get the value of T(n - 1), and retrieve the result of T(n - 2) and T(n - 3).
@param[in] n The n in T(n).
@param[out] mid Value of T(n - 2).
@param[out] right Value of T(n - 3).
@return Value of T(n - 1).
*/
int find_trib(int n, int & mid, int & right)
{
if (3 == n)
{
mid = 1;
right = 1;
return 2;
}
else
{
int temp;
mid = find_trib(n - 1, right, temp);
return mid + right + temp;
}
}
/** Find value of T(n).
@param[in] The n in T(n).
@return Value of T(n).
@note T(n) = T(n - 1) + T(n - 2) + T(n - 3) (n > 2)
T(0) = T(1) = 1, T(2) = 2.
*/
int tribonaci(int n)
{
if (n <>{
return 0; // Undefined feature.
}
if (0 == n 1 == n)
{
return 1;
}
if (2 == n)
{
return 2;
}
int mid, right;
int left = find_trib(n, mid, right);
return left + mid + right;
}
0 评论:
发表评论