N求和的不同组合
Different combinations of summands of N
程序应写出,N的自然和数有多少种不同的组合。所有的和数不大于,则K (N,K<=120)。我的程序只包含递归:
int F (int x,int s) // s- total number, which is necessary to lay down the terms of
{
if (s == 0) // when total number == 0
{
ans++;
return 0;
}
for (int i=x;i<=min(k,s);i++) // x - previous term
F(i,s-i); // we add a new summand -> subtract that number from the amount
}
和主体部分:
int main ()
{
cin >> n>> k;
F(1,n);
cout << ans;
}
那么,你能帮我把程序做得快一点吗?
您可以添加记忆。对于固定的x和s,不需要多次计算F。它需要稍微更改代码(使F实际返回计算值,而不是增加一个数值),并添加一个数组来保存已经计算过的值。
这是一个有趣的练习;
int F (int x,int s)
{
static map< int, map< int, int > > table;
if( (x==s) || (s==0) ) return 1;
if( x > s ) return 0;
auto itr1 = table.find(x);
if( itr1 != table.end() )
{
auto& sub = itr1->second;
auto itr2 = sub.find(s);
if( itr2 != sub.end() )
{
return itr2->second;
}
}
int ans=1;
for ( int i=x; i<s; ++i )
ans += F(i,s-i);
table[x][s]=ans;
return ans;
}
相关文章:
- 混合组合和继承的C++问题
- 给定一个向量,如何找到该向量的所有子集和的原始索引
- 通过组合不同的类型来创建唯一的id
- 这种用于查找连续子数组中最大和的递归算法有什么优势吗?
- 斐波那契数列部分和的最后一位数字
- 如何有效地找到数组中三元组和的最小差异?
- C++:试图通过组合和帕斯卡三角形来理解constexpr
- 组合"%"和可选后缀时,自动属性传播有时不起作用
- 计算校验和的逐位运算符
- 找到 2 个相等和的子序列,最大总和?
- 返回混合 \ 和 / 的文件系统路径字符串方法
- C++对象文件和程序文件组合编译的 Bashrc 别名
- 组合理论的一个问题
- *、/ 和 % 的定义如何保证 a/b * b + a%b == a
- 带有空格和","的Cin
- 如何正确组合类型的别名,功能指针和模板功能
- 可能的组合和循环
- 如何列出C++数组中所有可能的组合和
- 可以创建所有组合和这些组合的所有组的算法
- 继承、组合和多成员变量的优点/缺点