[英]What is the most efficient algorithm to find the closest prime less than a given number n?
[英]Find the numbers in a collection that add up to the number closest to n which is less than n
基本上我得到了一個數字向量和一個目標數字,目標是找到數組中的數字加起來最接近n的數字,即小於n,我應該能夠使用相同的數字向量多次。
例如:
{4, 3}, target: 10
在這種情況下,它應該以任意順序返回一個包含 3、3、4 的向量,因為它們的總和是 10
{60, 30}, target: 135
在這種情況下,它應該返回一個包含 60、60 或 30、30、30、30 的向量,因為它們的總和是最接近目標的總和,但仍小於目標。
我怎樣才能在現代 c++ 中制作這個算法?
我嘗試將https://stackoverflow.com/a/15496549/13879838解決方案修改為我想要的,但我被困在它使用遞歸的點上,我找不到一種方法來檢查解決方案是否比算法找到的前一個。
如果保證vec
中的所有數字都是正數,則可以使用遞歸輕松解決。
solve(vec, target, currentSum, solution)
if currentSum > target
return
if currentSum == target
print(solution)
return
for value in vec
solve(vec, target, currentSum + value, solution + value)
你從
solve({4, 3}, 10, 0, {})
solution + value
和currentSum + value
。
下一步是找到一種迭代方法並添加記憶
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.