计算从数组求和到特定数字所需的最少数字

时间:2019-08-29 09:16:29

标签: python arrays sum

我遇到了一个问题,给我一个数字数组[1,3,5],需要找到可以加到特定数字上的最少数量的数字。每个数字都有权重,我需要计算最有效的。例如,如果数字为6,我将需要使用[5,1]而不是[3,3],因为5的重要性更大。对于12,则为[5,5,1,1]而不是[3,3,3,3]

我已经尝试实现字典和数组,但是解决问题的部分是我遇到的麻烦。

2 个答案:

答案 0 :(得分:1)

一种有效的方法是不使用列表中的1,而是尝试使用尽可能多的最大数,然后递归地尝试获得余数:

如果找不到解决方案,该函数将返回None

def solve(numbers, target):
    '''Return a list of the largest of numbers whose sum is target, 
    None if impossible'''

    if not numbers:
        return None

    # make sure that numbers is sorted
    numbers = list(sorted(numbers))
    # get the largest number and remove it from the list
    largest = numbers.pop()
    # we start with as many times the largest number as possible
    quotient, remainder = divmod(target, largest)
    # did we reach the target?
    if remainder == 0:
            return [largest] * quotient

    # if not, try with a deacreasing number of times the largest    
    # (including 0 times)
    for n in range(quotient, -1, -1):
        remainder = target - n * largest
        # and recursively try to obtain the remainder with the remaining numbers
        solution = solve(numbers, remainder)
        if solution:
            return [largest] * n + solution
    else:
        return None

一些测试:

solve([1, 3, 5], 12)
# [5, 5, 1, 1]

solve([3, 5], 12) # no 1, we have to use smaller numbers
# [3, 3, 3, 3]

solve([7, 3, 4], 15)
# [7, 4, 4]

solve([3, 4], 5) # Impossible
# None

答案 1 :(得分:0)

通过取最大的数字,直到n = 0,再减小数字,保持循环,直到n =0。

如Thierry Lathuille所指出的那样,如果数组中没有1,这可能行不通。如果是这种情况,您可能想弄弄if n < 0

n = int(input())
a = [1, 3, 5]
ans = []
while n > 0:
    n -= max(a)
    if n == 0:
        ans.append(max(a))
        break
    if n > 0:
        ans.append(max(a))
    if n < 0:
        n += max(a)
        a.pop(a.index(max(a)))

print(ans)