c++ - 组合 SUM Max 5 因子 C++
问题描述
我有一个与获取 25 个数字组合的总和有关的问题。程序显示总和,但我不能将因子限制为 5。总和 = 100。
它显示了太多的数组和超过 5 个因子,其中“K”的总和为 100。数字不能重复。
这是代码:
// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
// Function to find all unique combination of
// given elements such that their sum is K
void unique_combination(int l, int sum, int K,
vector<int>& local, vector<int>& A)
{
// If a unique combination is found
if (sum == K) {
cout << "{";
for (int i = 0; i < local.size(); i++) {
if (i != 0)
cout << " ";
cout << local[i];
if (i != local.size() - 1)
cout << ", ";
}
cout << "}" << endl;
return;
}
// For all other combinations
for (int i = l; i < A.size(); i++) {
// Check if the sum exceeds K
if (sum + A[i] > K)
continue;
// Check if it is repeated or not
if (i and A[i] == A[i - 1] and i > l)
continue;
// Take the element into the combination
local.push_back(A[i]);
// Recursive call
unique_combination(i + 1, sum + A[i],
K, local, A);
// Remove element from the combination
local.pop_back();
}
}
// Function to find all combination
// of the given elements
void Combination(vector<int> A, int K)
{
// Sort the given elements
sort(A.begin(), A.end());
// To store combination
vector<int> local;
unique_combination(0, 0, K, local, A);
}
// Driver code
int main()
{
vector<int> A = { 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25 };
int K = 100;
// Function call
Combination(A, K);
return 0;
}
请您检查并让我知道我的错误在哪里?
先感谢您。
例如我得到的结果:
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 13, 15, 17} {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 14, 15, 16} {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 25} {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 21, 24}
但正如你所看到的,数组有超过 5 个元素(例如有 12 或 13 个)
解决方案
推荐阅读
- python - Python中按键分组的字典列表
- sql - 有什么方法可以改进我的 PostgreSQL 上的这个查询吗?
- django - 在调用部署之前查找静态文件是否存在 - Django
- python - 覆盖内置函数并将其转移到外部 python 脚本调用的方法(即 os.system("Script2.py"))
- python - Tkinter CheckButton 状态没有改变
- javascript - 展开选择以包括 AnchorNode 和 FocusNode 的所有文本
- javascript - 问一下jquery函数操作
- python - Python 命令历史记录在 PowerShell、Windows 中不起作用
- r - 提取每组中的最小值和最大值,并使用 R 添加新的文本列
- c++ - 如何节省 C++ DLL 的构建时间