首页 > 解决方案 > 组合 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 个)

标签: c++

解决方案


推荐阅读