使用DP添加到目标号码的给定号码的组合?

时间:2017-09-25 08:15:11

标签: javascript algorithm dynamic-programming

我不知道我是否正确描述了问题。问题是:有给定的数字:2,3,7,让我们说目标数是10.只使用这些给定的数字,找到加起来为10的组合。例如:2 + 2 + 2 + 2 + 2 = 10或3 + 7 = 10或7 + 3 = 10等

鉴于此,我想出了递归解决方案(使用Javascript):

function combination(n) {
  if(n < 2) {
    return 0
  }

  if(n === 2) {
    return 1
  }

  if(n === 3) {
    return 1
  }

  if(n === 7) {
    return 4
  }

  return combination(n - 2) + combination(n - 3) + combination(n - 7)
}

但是,此解决方案的时间呈指数级增长。所以我试图通过使用DP(动态编程)来解决这个问题。但是我想不出办法。

有什么想法吗?如果有人启发我,我将不胜感激。

2 个答案:

答案 0 :(得分:0)

您可以通过检查总和和索引来使用递归方法。如果值有效,则继续。

&#13;
&#13;
function combine(array, sum) {
    function iter(i, temp) {
        var total = temp.reduce((a, b) => a + b, 0);
        if (total === sum) {
            result.push(temp);
        }
        if (total >= sum || i >= array.length) {
            return;
        }
        iter(i, temp.concat(array[i]));
        iter(i + 1, temp);
    }

    var result = [];
    
    iter(0, []);
    return result;
}

console.log(combine([2, 3, 7], 10));  
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;
&#13;
&#13;

答案 1 :(得分:0)

谢谢你们,我已经通过使用迭代,自下而上来解决这个问题。

function combination(n) {
  var table = {
    '2': 1,
    '3': 1,
    '7': 4
  }
    if(n < 2) return 0
  if(table[n]) return table[n]

  for(let i = 4; i <= n; i++) {
    table[i] = (table[i - 2] ? table[i - 2] : 0) + (table[i - 3] ? table[i - 3] : 0) + (table[i - 7] ? table[i - 7] : 0)
  }
  return table[n]
}
相关问题