[英]Subsets of a given Set of Integers whose sum is a Constant N : Java
Given a set of integers, how to find a subset that sums to a given value...the subset problem?给定一组整数,如何找到总和为给定值的子集......子集问题?
Example: S = {1,2,4,3,2,5} and n= 7 Finding the possible subsets whose sum is n.示例: S = {1,2,4,3,2,5} 和 n= 7 查找总和为 n 的可能子集。 I tried to google out found many links,but were not clear.我试图用谷歌搜索发现很多链接,但不清楚。 How can we solve this in java and what is the data structure to be used and its complexity?我们如何在 java 中解决这个问题,要使用的数据结构及其复杂性是什么?
In three steps:分三步:
Find the powerset of S (the set of all subsets of S)求 S 的幂集(S 的所有子集的集合)
Compute the sum of each subset计算每个子集的总和
Filter out subsets that did not sum to 7.过滤掉总和不等于 7 的子集。
I wont give you any code, but explain how it works.我不会给你任何代码,但会解释它是如何工作的。
0 to (2^k-1)
运行从0 to (2^k-1)
的循环The above method will evaluate each possible subset of the given set.上述方法将评估给定集合的每个可能子集。
If the upper limit of the values is small, then Dynamic Programming Approach could be used.如果值的上限很小,则可以使用动态规划方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.