Efficient algorithm to calculate the sum of all k-products

前端 未结 6 1930
青春惊慌失措
青春惊慌失措 2021-02-06 04:49

Suppose you are given a list L of n numbers and an integer k. Is there an efficient way to calculate the sum of all products of

6条回答
  •  清酒与你
    2021-02-06 05:40

    You can reduce k by 1:

    e.g. for k=2

    1*3 + 1*4 + 1*6 + 3*4 + 3*6 + 4*6
    

    ==

    1*(3+4+6)+3*(4+6)+4*6
    

    and for k=3

    1*3*4 + 1*3*6 + 3*4*6
    

    ==

    1*3*(4+6) + 3*4*6
    

    So basically you cycle your list, then recurse to the same algorithm with k reduced by 1 and only the rest of the list

提交回复
热议问题