For a given integer a, find all unique combinations of positive integers that sum up to a

后端 未结 2 1492
悲&欢浪女
悲&欢浪女 2021-02-03 13:57

Not a homework question. I was going through the questions here and I came across this question. Someone has answered it. I have tried a lot to understand the recursion used but

2条回答
  •  日久生厌
    2021-02-03 14:43

    Leaving the solution aside for moment and looking at the problem itself:

    Compare this problem to insertion sort for an array(or any recursive algorithm). In insertion sort at any point during the execution we have a part of the array that is sorted and another part that is unsorted. We pick an element from the unsorted part and find it's place in the sorted part, thereby extending the sorted part, making the problem smaller.

    In case of this problem, we have a fixed number of elements we can choose from i.e integers 1 to the number in the problem(let's call it N), to be a part of the sequence that sums up to N.

    At any point we have collected some numbers that sum up to less than N(say X), reducing the problem to N-X size, also reducing our choices from 1..N to 1..(N-X) for the next recursion.

    The solution does the obvious, making each choice from 1 to (N-X) and proceeding recursively till X=N. Every time the algorithm reaches X=N, means a permutation is found.

    Note: One problem I see with the solution is that it needs to know the number of permutations that will be found beforehand. int a[5]; This could cause problems if that value is unknown.

提交回复
热议问题