java - 动态规划——求公式

标签 java recursion dynamic-programming

我无能为力地试图解决这个问题:

Let arr be an array of integers of length n (indexed from 1 to n).

Let M[s][i] be a matrix containing boolean values of, if there exist a subset of first i numbers of the array arr (arr[1], arr[2], ..., arr[i], ..., arr[n]), of which the sum is exactly s.

Find the recursive formula for the value of M[s][i] based on M[?][j], where j < i and arr contains j. You can assume that M[s][0] = 0.

如何找到这个公式?如果有任何帮助,我将不胜感激。

最佳答案

基于您的 M[s][i] 定义的简单递归公式为:

M[s][i] = M[s][i-1] || M[s-arr[i]][i-1]

说明

  • 如果 arr[i] 不包含在子集中,则 M[s][i]true 如果 存在第一个 i-1 元素的子集,其总和为 完全等于s
  • 如果 arr[i] 包含在子集中,则 M[s][i] 仅当存在第一个的子集时才为 true i - 1 个元素,其子集完全等于 s - arr[i]

这个问题通常被称为子集和问题。它已经有多个答案 here

关于java - 动态规划——求公式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55871544/

相关文章:

java - 如何显示两个对象列表之间的唯一元素?

javascript - 递归对象 - Javascript

Python 使用递归打印输出

algorithm - 二进制数的子集和

algorithm - 是否有多项式算法可以找到整数到区间的分配?

Java - 使用 binarySearch 查找数组中特定元素的出现次数,无需 If

java - 短于 int 转换,奇怪的行为

java - 如何向服务请求许可

assembly - MAC-1 汇编递归

python - 使用动态规划在网格中从左上角到右下角的最大和路径