algorithm - 从 1 到 k 中选择数字使其总和等于 n 的方法有多少?
问题描述
问题如下:给定 n (1->1000) 和 k(1->100),找出从 1 到 k 中选取数字的可能方法数,使它们的总和等于 n。
这是一个例子:
n = 5; k = 3;
可能的方式:
1*3 + 1*2 = 5
1*3 + 2*1 = 5
1*2 + 3*1 = 5
2*2 + 1*1 = 5
5*1 = 5
==> 我们有 5 种可能的方法
我尝试过组合,写下许多示例以找到通用解决方案,但没有运气。
请帮我解决这个问题,谢谢!
解决方案
您描述的问题称为分区。它需要重复才能得到解决方案。我从这个问题中调整了我的解决方案,其中包含对这个想法的详细解释。请小心,因为这个数字增长得非常快,例如对于 n = 100 和 k = 6,您将得到 189509 个可能的总和。这是 C++ 中的代码:
#include <string>
#include <algorithm>
int nrOfSums = 0;
void partition(int n, int max, std::string prefix) {
if (n == 0) {
std::cout<<prefix<<std::endl;
nrOfSums++;
return;
}
for (int i = std::min(max, n); i >= 1; i--) {
partition(n - i, i, prefix + " " + std::to_string(i));
}
}
void partition(int n, int k) {
partition(n, k, "");
}
int main()
{
int n = 8, k = 3;
partition(n, k);
std::cout << "number of possible sums: "<< nrOfSums;
}
n = 8, k = 3 的输出:
3 3 2
3 3 1 1
3 2 2 1
3 2 1 1 1
3 1 1 1 1 1
2 2 2 2
2 2 2 1 1
2 2 1 1 1 1
2 1 1 1 1 1 1
1 1 1 1 1 1 1 1
number of possible sums: 10
推荐阅读
- mysql - Laravel - 如何使用与所选客户 ID 相关联的地址自动填充表单中的文本输入?
- django - Django:如何根据一对多孩子中的值进行过滤
- python - 使用熊猫具有不同列的多个文件
- css - 如何沿页面浮动侧导航
- python - 如何用 Rich 替换/扩展 Django shell?
- jms - 如何配置到 Artemis 的 WebLogic JMS 消息传递桥
- c++ - C ++陷入相等运算符分配的无限循环
- python - 在 Fastapi 应用程序上使用 loguru-log 请求参数进行 Python 日志记录
- jquery - 无法验证 vue.js 中的字段
- c++ - 检查一个字符是否在字符串中至少出现 N 次。算法中的任何解决方案?