cpp-algo-cases/chapter_computational_compl.../recursion.cpp

79 lines
1.5 KiB
C++
Raw Normal View History

2024-02-20 16:13:23 +08:00
/**
* File: recursion.cpp
* Created Time: 2023-08-24
* Author: krahets (krahets@163.com)
*/
#include "../utils/common.hpp"
/* <20>ݹ<EFBFBD> */
int recur(int n) {
// <20><>ֹ<EFBFBD><D6B9><EFBFBD><EFBFBD>
if (n == 1)
return 1;
// <20>ݣ<EFBFBD><DDA3>ݹ<EFBFBD><DDB9><EFBFBD><EFBFBD><EFBFBD>
int res = recur(n - 1);
// <20><EFBFBD><E9A3BA><EFBFBD>ؽ<EFBFBD><D8BD><EFBFBD>
return n + res;
}
/* ʹ<>õ<EFBFBD><C3B5><EFBFBD>ģ<EFBFBD><C4A3><EFBFBD>ݹ<EFBFBD> */
int forLoopRecur(int n) {
// ʹ<><CAB9>һ<EFBFBD><D2BB><EFBFBD><EFBFBD>ʽ<EFBFBD><CABD>ջ<EFBFBD><D5BB>ģ<EFBFBD><C4A3>ϵͳ<CFB5><CDB3><EFBFBD><EFBFBD>ջ
stack<int> stack;
int res = 0;
// <20>ݣ<EFBFBD><DDA3>ݹ<EFBFBD><DDB9><EFBFBD><EFBFBD><EFBFBD>
for (int i = n; i > 0; i--) {
// ͨ<><CDA8><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ջ<EFBFBD><D5BB><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ģ<EFBFBD><EFBFBD>ݡ<EFBFBD>
stack.push(i);
}
// <20><EFBFBD><E9A3BA><EFBFBD>ؽ<EFBFBD><D8BD><EFBFBD>
while (!stack.empty()) {
// ͨ<><CDA8><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ջ<EFBFBD><D5BB><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ģ<EFBFBD><EFBFBD>
res += stack.top();
stack.pop();
}
// res = 1+2+3+...+n
return res;
}
/* β<>ݹ<EFBFBD> */
int tailRecur(int n, int res) {
// <20><>ֹ<EFBFBD><D6B9><EFBFBD><EFBFBD>
if (n == 0)
return res;
// β<>ݹ<EFBFBD><DDB9><EFBFBD><EFBFBD><EFBFBD>
return tailRecur(n - 1, res + n);
}
/* 쳲<><ECB3B2><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>У<EFBFBD><D0A3>ݹ<EFBFBD> */
int fib(int n) {
// <20><>ֹ<EFBFBD><D6B9><EFBFBD><EFBFBD> f(1) = 0, f(2) = 1
if (n == 1 || n == 2)
return n - 1;
// <20>ݹ<EFBFBD><DDB9><EFBFBD><EFBFBD><EFBFBD> f(n) = f(n-1) + f(n-2)
int res = fib(n - 1) + fib(n - 2);
// <20><><EFBFBD>ؽ<EFBFBD><D8BD><EFBFBD> f(n)
return res;
}
/* Driver Code */
int main() {
int n = 5;
int res;
res = recur(n);
cout << "\n<EFBFBD>ݹ麯<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ͽ<EFBFBD><EFBFBD><EFBFBD> res = " << res << endl;
res = forLoopRecur(n);
cout << "\nʹ<EFBFBD>õ<EFBFBD><EFBFBD><EFBFBD>ģ<EFBFBD><EFBFBD><EFBFBD>ݹ<EFBFBD><EFBFBD><EFBFBD><EFBFBD>ͽ<EFBFBD><EFBFBD><EFBFBD> res = " << res << endl;
res = tailRecur(n, 0);
cout << "\nβ<EFBFBD>ݹ麯<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ͽ<EFBFBD><EFBFBD><EFBFBD> res = " << res << endl;
res = fib(n);
cout << "\n<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>еĵ<EFBFBD> " << n << " <20><>Ϊ " << res << endl;
return 0;
}