Home > Backend Development > PHP Tutorial > Find all combinations that sum to n

Find all combinations that sum to n

WBOY
Release: 2016-08-08 09:06:36
Original
2291 people have browsed it

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>
Copy after login
Copy after login

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>
Copy after login
Copy after login

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>
Copy after login

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

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template