题目示意:
分析:
解答源码:
class solution
{
public:
int max3(int a, int b, int c)
{
return max(a, max(b, c));
}
std::vector<int> mem;
int get1(int x)
{
if (x == 1)
{
return 1;
}
if (x == 2)
{
return 1;
}
if (x == 3)
{
return 2;
}
if (mem[x] != -1)
{
return mem[x];
}
int res = -1;
for (int i = 1; i <= x-1;i++)
{
res = max3(res, i*get1(x - i), i*(x - i));
}
mem[x] = res;
return res;
}
//动态规划法
int dongtaiguihua(int n)
{
mem = std::vector<int>(n + 1, -1);
mem[1] = 1;
for (int i = 2; i <= n;i++)
{
//i-j +j
for (int j = 1; j < i;j++)
{
mem[i] = max3(mem[i], (i - j)*j, mem[i - j] * j);
}
}
return mem[n];
}
//记忆化搜索
int getres(int n)
{
mem = std::vector<int>(n + 1, -1);
return get1(n);
//return res;
}
};
void main()
{
solution s;
int n = s.getres(10);
cout << n << endl;
cout << s.dongtaiguihua(10) << endl;
system("pause");
}
结果: