简体   繁体   English

是动态编程还是分而治之?

[英]Is this dynamic programming or divide and conquer?

I'm in the middle of studying algorithms. 我正在研究算法。 There is an article I read indirectly discussing the knapsack problem. 我读过一篇间接讨论背包问题的文章。 In the end it is said to be solved with dynamic programming but to me it looks like just divide and conquer with minor optimizations. 最后,据说可以通过动态编程来解决,但对我来说,它看起来像是通过较小的优化进行分而治之。 Can someone have a look? 可以看看吗? I have pasted the code into a bin http://jsbin.com/sulipipole/edit?js,console . 我已将代码粘贴到bin http://jsbin.com/sulipipole/edit?js,console中

const ACTIVITIES = [
  {name: 'side-project', time: 10, xp: 12},
  {name: 'algorithms', time: 3, xp: 7},
  {name: 'networking', time: 1, xp: 0.5},
  {name: 'exercise', time: 2, xp: 1.5},
  {name: 'systems design', time: 4, xp: 4},
  {name: 'making CSS codepens', time: 3, xp: 4}
];


const findJob = function(time, activities) {

    const optimalSolution = function(items, n = items.length, timeLeft = time) {

    if (n === 0 || timeLeft === 0) {
      return [];
    }

    if (items[n - 1].time > timeLeft) {
      return optimalSolution(items, n - 1, timeLeft);
    }

     const lastItem = items[n - 1];

    const withLastItem = [
      lastItem,
      ...optimalSolution(items, n - 1, timeLeft - lastItem.time)
    ];
    const withoutLastItem = optimalSolution(items, n - 1, timeLeft);

    if (totalXp(withLastItem) > totalXp(withoutLastItem)) {
      return withLastItem;
    } else {
      return withoutLastItem;
    }
    };

    const totalXp = arr => arr.reduce((total, ea) => total + ea.xp, 0);

    const sortedByTime = activities
      .slice()
      .sort((a, b) => a.time - b.time);

    return optimalSolution(sortedByTime)
      .map(act => act.name);
    };

Dynamic programming requires some memoization or tabling scheme correct? 动态编程需要一些记忆或制表方案正确吗?

I really like the way Skiena described dynamic programming in his book "the algorithm design manual". 我真的很喜欢Skiena在他的《算法设计手册》一书中描述动态编程的方式。 "Dynamic programming is a technique for efficiently implementing a recursive algorithm by storing partial results". “动态编程是一种通过存储部分结果来有效实现递归算法的技术”。

You have a recursive algorithm here but no storing of partial results. 您这里有一个递归算法,但没有存储部分结果。 So it is not dynamic programming. 因此它不是动态编程。 But it can probably be turned into a dynamic programming algorithm by storing and reusing the partial results. 但是通过存储和重用部分结果,可以将其转变为动态编程算法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM