jeudi 21 janvier 2021

Find the numbers in a collection that add up to the number closest to n which is less than n in c++

Basically I'm given a vector of numbers and a target number where the goal is to find the numbers in the array that add up to the number closest to n, that is less than n and I should be able to use the same number in the vector multiple times.

For example:

{4, 3}, target: 10

In this case it should return a vector containing 3, 3, 4 in any order because their sum is 10

{60, 30}, target: 135

In this case it should return a vector containing either 60, 60 or 30, 30, 30, 30 because the sum of these is the closest sum to the target possible while it is still less than the target.

How could I make this algorithm in modern c++?

I have tried modifying https://stackoverflow.com/a/15496549/13879838 solution to what I want but I got stuck at the point that it uses a recursion and I can't find a way to check whether a solution is better than the previous one found by the algorithm.

Aucun commentaire:

Enregistrer un commentaire