gpt4 book ai didi

java - 给定一个数组,找到总和为值 k 的所有子集

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:47:00 24 4
gpt4 key购买 nike

很简单的问题:

Given an array, find all subsets which sum to value k

我正尝试在 Java 中执行此操作,并且似乎找到了一个可以在 O(n^2) 时间内解决它的解决方案。这个解决方案是正确的 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();
}
}
}

我已经用各种例子尝试过它,但没有发现任何似乎可以破坏它的东西。然而,当我在网上搜索时,这似乎不是问题的常见解决方案,许多解决方案都声称这个问题是 O(2^n)。

附言这不是家庭作业问题,我是一名程序员,我的工作是尝试在 Java 中研究我的 Comp Sci 基础知识。谢谢!

最佳答案

不,这是不正确的。举这个简单的例子

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).

我会引用 wiki

关于java - 给定一个数组,找到总和为值 k 的所有子集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18158544/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com