Home  >  Article  >  Backend Development  >  Find all combinations that sum to n

Find all combinations that sum to n

WBOY
WBOYOriginal
2016-08-08 09:06:362237browse

Given a number n

Requirements:
(1) The value of the integer on the left side of the equation is 1~n-1.
(2) It is required that the sum of the left side of the equation is n.

<code>若 n = 3;
1 + 1 + 1 = 3;
1 + 2 = 3;</code>

Reply content:

Given a number n

Requirements:
(1) The value of the integer on the left side of the equation is 1~n-1.
(2) It is required that the sum of the left side of the equation is n.

<code>若 n = 3;
1 + 1 + 1 = 3;
1 + 2 = 3;</code>

The poster can go and learn the general function

This should be a template question for the parent function

<code>function calcN (n) {
    var res = [],
        cache = {};

    loop(n);

    function loop(k, arr) {
        arr = arr || [];
        var i = 1, count = k / 2 | 0;
        cache[k] = true;
        while (i <= count) {
            
            res.push(arr.concat([i, k - i]));

            if (!cache.hasOwnProperty(i)) {
                loop(i, [k - i].concat(arr));
            }

            if (!cache.hasOwnProperty(k - i)) {
                loop(k - i, [i].concat(arr));
            }

            i++;        
        }
  }
  return res;
}
// 测试部分:
console.log(calcN(5));
// 输出
[ [ 1, 4 ],
  [ 1, 1, 3 ],
  [ 1, 1, 1, 2 ],
  [ 1, 1, 1, 1, 1 ],
  [ 1, 2, 2 ],
  [ 2, 3 ] ]</code>

For C++, just modify it based on the above, use map and vector

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn