[英]Given an array, find all subsets which sum to value k
pretty simple question: 很简单的问题:
Given an array, find all subsets which sum to value k 给定一个数组,找到总和为值k的所有子集
I am trying to do this in Java and seem to have found a solution which solves it in O(n^2) time. 我正在尝试用Java执行此操作,并且似乎找到了可以在O(n ^ 2)时间内解决它的解决方案。 Is this solution a correct O(n^2) implementation? 此解决方案是正确的O(n ^ 2)实现吗?
@Test
public void testFindAllSubsets() {
int[] array = {4,6,1,6,2,1,7};
int k=7;
// here the algorithm starts
for(int i = 0; i < array.length;i++){
// now work backwords
int sum = array[i];
List<Integer> subset = new ArrayList<Integer>();
subset.add(array[i]);
for(int j = array.length -1; j > i && sum < k; j--){
int newSum = sum + array[j];
// if the sum is greater, than ditch this subset
if(newSum <= k){
subset.add(array[j]);
sum = newSum;
}
}
// we won't always find a subset, but if we do print it out
if(sum == k){
System.out.print("{");
System.out.print(subset.get(0));
for(int l = 1; l < subset.size(); l++){
System.out.print(","+subset.get(l));
}
System.out.print("}");
System.out.println();
}
}
}
I have tried it with various examples and have not found any that seem to break it. 我已经通过各种示例对其进行了尝试,但没有发现任何可能破坏它的示例。 However, when I have searched online, this does not appear to be the common solution to the problem, and many solution claim this problem is O(2^n). 但是,当我在线搜索时,这似乎并不是该问题的常见解决方案,许多解决方案都声称此问题为O(2 ^ n)。
PS This is not a homework question, I'm a brogrammer with a job trying to work on my Comp Sci fundamentals in Java. PS:这不是一个作业问题,我是一名笨拙的人,他的工作是尝试使用Java构建我的Comp Sci基础知识。 Thanks! 谢谢!
No this is not correct.Take this simple example 不,这不正确。以这个简单的例子为例
Your array is 4,6,1,2,3,1 and target sum is 7 then in your logic it would only find (4,3) (6,1) (1,2,3,1) your code would miss (4,2,1), (4,3). 您的数组是4,6,1,2,3,1并且目标总和是7,那么在您的逻辑中它将仅找到您的代码会丢失的(4,3)(6,1)(1,2,3,1) (4,2,1),(4,3)。
An elegant solution is to simply think of a subset as each member answering the question "Am I in or not?" 一个优雅的解决方案是简单地将一个子集视为每个成员在回答“我是否参加?”这个问题。 So essentially each can answer yes/no, so you have 2 N subsets(including the empty subset). 因此,基本上每个人都可以回答“是/否”,因此您有2个N子集(包括空子集)。 The most natural way to code this up is to recurse through each element and do one of the following: 进行编码的最自然的方法是遍历每个元素并执行以下操作之一:
Thus the time complexity is O(2 N ) simply because you have so many answers possible in the worst case. 因此,时间复杂度为O(2 N )仅仅是因为您在最坏的情况下有这么多答案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.