Finding all possible combinations of numbers to reach a given sum

前端 未结 30 3762
一个人的身影
一个人的身影 2020-11-21 06:39

How would you go about testing all possible combinations of additions from a given set N of numbers so they add up to a given final number?

A brief exam

30条回答
  •  别那么骄傲
    2020-11-21 07:11

    Here is a better version with better output formatting and C++ 11 features:

    void subset_sum_rec(std::vector & nums, const int & target, std::vector & partialNums) 
    {
        int currentSum = std::accumulate(partialNums.begin(), partialNums.end(), 0);
        if (currentSum > target)
            return;
        if (currentSum == target) 
        {
            std::cout << "sum([";
            for (auto it = partialNums.begin(); it != std::prev(partialNums.end()); ++it)
                cout << *it << ",";
            cout << *std::prev(partialNums.end());
            std::cout << "])=" << target << std::endl;
        }
        for (auto it = nums.begin(); it != nums.end(); ++it) 
        {
            std::vector remaining;
            for (auto it2 = std::next(it); it2 != nums.end(); ++it2)
                remaining.push_back(*it2);
    
            std::vector partial = partialNums;
            partial.push_back(*it);
            subset_sum_rec(remaining, target, partial);
        }
    }
    

提交回复
热议问题