Finding all the number combos in array that add up to input number

前端 未结 1 570
春和景丽
春和景丽 2021-01-16 20:40

Hey I\'m working on figuring out an algorithm that takes a user-entered number and then goes through an array of size 50 filled with random numbers between 1 and 100 and fin

1条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-16 20:55

    This is an idea, I don't have a working code. Try to use recursion, test all combinations with the biggest possible number plus all the rest without it. Function like: Sums(Number, maxN), (maxN is maximum number which we can take - in first call it's 9) For your example would be:
    1. As suggested, sort them and cut bigger than input.
    2. Check if the maxN is greater than the minimum required to make a sum, in your example it is 5 (can't make 9 from numbers smaller than 5 in your set); if it's not return (base case).
    3. Is maxN equal tu input? (9 in first call)
    a) Yes - first solution subset [9] + Sums(Number, dec(maxN)) (dec(maxN) will be 6 in first call)
    b) No - recursively check if 'Number - maxN' could be built from numbers from your set, Sums(Number - maxN, dec(K) or max number of 'Number - maxN' (depends what is smaller)) + Sums(Number, dec(maxN)) - add the rest.

    Here is code to count only, ways to write a number as sum of squares, it passed HackerRank tests:

    import math
    def minArgument(x):
        s = 0
        i = 1
        while s < x:
            s = s + i * i
            i = i + 1
        return i - 1
    def maxPower(a):
        return math.floor(math.sqrt(a))
    def sumOfSquares(M, K, cnt):
        if M < 1:
            return cnt
    lowerLimit = minArgument(M)
        if K < lowerLimit:
            return cnt
        else:
            if K * K == M:
            return sumOfSquares(M, K - 1, cnt + 1)
        else:
            return  sumOfSquares(M, K - 1,sumOfSquares(M - K * K,  
                        min(maxPower(M - K * K), K - 1), cnt))
    

    After easy change, this gives you number of solutions. I don't see how to build a list with combinations as a return value now...

    0 讨论(0)
提交回复
热议问题