简体   繁体   English

给定整数集的子集,其和为常数 N:Java

[英]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:分三步:

  1. Find the powerset of S (the set of all subsets of S)求 S 的幂集(S 的所有子集的集合)

  2. Compute the sum of each subset计算每个子集的总和

  3. Filter out subsets that did not sum to 7.过滤掉总和不等于 7 的子集。

I wont give you any code, but explain how it works.我不会给你任何代码,但会解释它是如何工作的。

  1. Run a loop from 0 to (2^k-1)运行从0 to (2^k-1)的循环
  2. For each value in 1, a 1 in its binary representation indicates that this value is chosen and 0 otherwise.对于 1 中的每个值,其二进制表示中的 1 表示选择该值,否则为 0。
  3. Test to see if the sum of chosen numbers is equal to n .测试以查看所选数字的总和是否等于n

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.

相关问题 给定一组n个整数,返回总和为0的k个元素的所有子集 - given a set of n integers, return all subsets of k elements that sum to 0 java-查找总和为给定数字的整数序列 - java - find sequence of integers whose sum is that of a given number 查找总计为n的集合的所有子集 - Find all subsets of a set that sum up to n 给定一个整数数组和一个总和,任务是找出给定数组的子集是否存在总和等于给定总和的子集 - Given an array of integers and a sum, the task is to find if there exists a subsets of given array with sum equal to given sum 在 java 中查找给定集合的所有子集,并按此顺序 - finding all subsets of a given set in java and in this order 查找给定大小为n的大小为k的子集 - Finding subsets of size k for a given set of size n 如何计算小于n且总和大于n * 2的3个整数的组合数? - How to calculate the number of combinations of 3 integers less than n whose sum is greater than n * 2? 查找具有给定总和的数字子集 - Finding Subsets of Numbers with a Given Sum 给定整数数组,找到所有“最大”子集 - Given an array of integers find all “maximal” subsets 回溯 - 给定一组数字,找到总和等于 M 的所有子集(给定 M) - Backtracking - Given a set of numbers, find all the subsets with a sum equal to M (M is given)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM