js dynamic programming algorithm

Dynamic Programming (DP for short) is a commonly used algorithmic idea for solving optimization problems. It is usually used to solve problems with overlapping subproblem properties and optimal substructure properties.

Here is an example showing how to use the dynamic programming algorithm to solve the knapsack problem:

function knapsack(items, capacity) {
  const n = items.length;
  const dp = Array(n + 1).fill(Array(capacity + 1).fill(0));

  for (let i = 1; i <= n; i++) {
    const weight = items[i - 1].weight;
    const value = items[i - 1].value;
    for (let j = 1; j <= capacity; j++) {
      if (weight <= j) {
        dp[i][j] = Math.max(value + dp[i - 1][j - weight], dp[i - 1][j]);
      } else {
        dp[i][j] = dp[i - 1][j];
      }
    }
  }

  return dp[n][capacity];
}

const items = [
  { weight: 2, value: 6 },
  { weight: 2, value: 10 },
  { weight: 3, value: 12 }
];
const capacity = 5;

console.log(knapsack(items, capacity)); // 输出:22

The above example solves a knapsack problem with three items, each with a corresponding weight and value. We need to choose items that maximize the total value for a given knapsack capacity. In dynamic programming, a two-dimensional array `dp` is used to save the state, where `dp[i][j]` represents the maximum value that can be obtained when the knapsack capacity is `j` among the first `i` items. value. By filling this two-dimensional array, we can get the final maximum value.

Hope the above examples can help you understand the dynamic programming algorithm. If you have further questions, feel free to ask!
 

おすすめ

転載: blog.csdn.net/weixin_39273589/article/details/132539486