Get all numbers that add up to a number

后端 未结 4 1074
情深已故
情深已故 2020-12-02 23:50

I\'m trying to find a way to display all the possible sets of X integers that add up to a given integer. for example to get all 2 integer sets that make 5 I would have:

4条回答
  •  青春惊慌失措
    2020-12-02 23:59

    Your question can be rephrased like this :

    Given a number N, find all sets [S1, S2, S3 .....] where the sum of each set equals N. The size of the sets are given by the number L.


    First let's consider the case of L=2.This means that you can have the following sets

    (9,1) , (8,2), (7,3) , (6,4) , (5,5)

    I'll call this the base solution and you'll soon see why.

    Let's change our L to 3 now and redo our answer :

    So let's consider the number 9. Does there exist such a list L such that sum(L) + 9 = 10 ? The obvious answer is No, but what's interesting here is not the answer but the question itself. We are basically asking for a set of 2 elements that can be summed up to be the number 1. This is the same problem that was solved by the base solution.

    So therefore for each number x in [9,8,7,6,5,4,3,2,1] you try to find a set [a,b]such that x+a+b = 10.

    This isn't a complete answer, but the idea is that you see the pattern here, and use recursion to calculate the base case as done above and then figure out the recursive call that will complete your solution. Good luck!

提交回复
热议问题