Newyorkcity
V2EX  ›  问与答

请问给出一个数组,返回使用该数组可能得到的所有的和(和这个数组本身),代码该怎么写?

  •  
  •   Newyorkcity · Mar 3, 2020 · 2017 views
    This topic created in 2290 days ago, the information mentioned may be changed or developed.
    比如给出 new int[]{1,2,3}
    那么返回
    {1,2,3,1+2,1+3,2+3,1+2+3}
    元素不能重复使用,但可能给出 new int[]{1,1,2,3} 这样 1+1 也对

    谢谢告知
    4 replies    2020-03-03 12:32:16 +08:00
    black
        1
    black  
       Mar 3, 2020
    回溯算法
    ASpiral
        2
    ASpiral  
       Mar 3, 2020
    zjbztianya
        3
    zjbztianya  
       Mar 3, 2020
    for mask = 1, 2^n-1 ,把 mask 看成二进制,如果对应位是1,那么把对应的数组的数字取出来....不过用 dfs 也行,要么取,要么不取
    rabbbit
        4
    rabbbit  
       Mar 3, 2020   ❤️ 1
    function coll(list) {
    const result = [];
    list.forEach(num => {
    for (let j = 0, len = result.length; j < len; j++) {
    result.push(num + result[j]);
    }
    result.push(num);
    });
    return result;
    }
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2399 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 49ms · UTC 16:10 · PVG 00:10 · LAX 09:10 · JFK 12:10
    ♥ Do have faith in what you're doing.