#include <iostream>
int function(int x, int n)
{
int result = 1;
for(int i = 0;i < n; i++)
{
result = result * x;
}
return result;
}
int function2(int x, int n)
{
if (n == 0)
{
return 1;
}
return function2(x,n-1)*x;
}
int function3(int x, int n)
{
if (n == 0)
{
return 1;
}
int result = function3(x,n/2);
if (n % 2 == 1)
{
return result * result * x;
}
return result * result;
}
int main() {
std::cout << "请输入x和n的值";
int x;
int n;
std::cin >> x >> n;
std::cout << x << "的" << n << "次方是" << function3(x,n) << std::endl;
}
如上图所示,function为非递归的解法,算法复杂度为O(n)
function2为递归解法,算法复杂度为O(n)
function3为递归解法,算法复杂度为O(logn)因为他将中间部分用一个局部变量进行保存了
具体思路可以参考动态规划的思路,因为动态规划本身就是递归+备忘录,就是把递归过程中的一部分结果存储在数组或者其他数据类型中
代码源自代码随想录第二章~