此题我们可以用记忆化搜索来解决
直接上代码解释吧
#include <iostream>
#include <cstring>
using namespace std;
const int N = 1e6 + 7;
long dfs(int x, int y);
int n, m, a[105], c[105][105];
int main()
{
memset(c, -1, sizeof(c));//初始化
cin >> n >> m;
for (int i = 1; i <= n; i++)
cin >> a[i];
cout << dfs(1, m);
return 0;
}
long dfs(int x, int y)
{
int ans = 0;
if (y==0)//没有空位了
ans = 0;
else if (c[x][y] != -1)//如果已被标记,则直接赋值
ans = c[x][y];
else
{
if (x == n)//已经是最后一种花的情况
{
if (y <= a[x]) ans++;//此时表示有一种解决方案出现
if (ans >= N)
{
ans %= N;
}
}
else
{
if (y <= a[x]) ans++;//同上
if (ans >= N)
{
ans %= N;
}
for (int i = 0; i <= a[x] && i <= y; i++)//每种情况都搜索一遍
{
ans += dfs(x + 1, y - i);
if (ans >= N)
{
ans %= N;
}
}
}
c[x][y] = ans;//赋值并标记
}
return ans;
}