子集和问题的有趣变化

发布于 2024-09-30 10:09:29 字数 172 浏览 1 评论 0原文

工作中的一个朋友向我提出了子集和问题的一个有趣的变体:

给定一组大小为 n 的正整数集合 S 以及整数 a 和 K,是否存在一个子集 R(集合 S 的)包含 <恰好有一个元素,其总和等于 K?

他声称这可以以时间复杂度 O(nka) 完成,我无法想出实现这个运行时间的动态规划算法。能做到吗?

An interesting variation of the subset sum problem was presented to me by a friend from work:

Given a set S of positive integers, of size n, and integers a and K, is there a subset R (of the set S) that contains exactly a elements, whose sum is equal to K?

He claims that this can be done with time complexity O(nka), I was unable to come up with a dynamic programming algorithm that achieved this running time. Can it be done?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

这样的小城市 2024-10-07 10:09:29

如果 k 和 a 足够小,那么我们就可以声明一个数组。

bool found[a][k]

您将迭代 S 中的每个值,并迭代 found 数组中的每个状态以获得新状态。

比如说,对于索引 a=1 和 k = 7,并且 S 的当前值为 7,

如果found[1][7] 为真,那么您也可以确定found[2][14] 也是真的。

当迭代结束时,您所需要做的就是检查 [a][k] 是否为真。

It can be done if k and a are small enough, so that we can declare an array

bool found[a][k]

You would iterate over each value in S and iterate over every state in the found array to obtain a new state.

Say, for the indexes of a=1 and k = 7, and the current value from S being 7,

if found[1][7] is true, then you can also be sure that found[2][14] is also true.

When the iteration ends, all you need to do is check that [a][k] is true or not.

压抑⊿情绪 2024-10-07 10:09:29

设 S = {s1,\ldots,sn}

设 P(j,K,a) 为真,当且仅当可以在 s1,\ldots,sj 中找到总和为 K 的元素。

则 P(j,K, a) = P(j-1, K-sj, a-1) OR P(j, K, a) (sj 要么需要,要么不需要)。

该算法包括用 K+1 和 a+1 填充维度为 n 的 3-D 表。每个条目需要恒定的时间来填充,因此时间(和空间)复杂度为 O(nKa)

Let S = {s1,\ldots,sn}

Let P(j,K,a) be true iff it is possible to find a elements in s1,\ldots,sj that sum up to K.

Then P(j,K,a) = P(j-1, K-sj, a-1) OR P(j, K, a) (either sj is needed or it is not needed).

The algorithm then consists of filling out 3-D table of dimension n by K+1 by a+1. Each entry takes constant time to fill, hence the time (and space) complexity is O(nKa)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文