[英]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
[英]Sum exists in array items
建議我有以下數組:
{2,3,4,5,11,6}並且我想知道數組的任何項是否包含數字x的總和。
例如:x = 10,則輸出將為{2,3,5}和{4,6}。 x = 13,那么輸出將為{2,11},{3,4,6}和{2,5,6}
解決該問題的最佳算法是什么?
我已經考慮過使用數組的可能排列來解決此問題,並檢查每個排列開始的總和是否等於X,但似乎無法解決。
謝謝!
我的兩分錢解決方案
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class Test {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(2, 3, 4, 5, 11, 6);
Collections.sort(list);
Integer sum = 0;
Integer max = 13;
for (int i=0; i<list.size(); i++) {
sumNext(list, i, sum,max, new ArrayList<Integer>());
}
}
private static void sumNext(List<Integer> list, int pos, Integer currentSum, Integer max,
List<Integer> currentElement) {
int nextSum = currentSum + list.get(pos);
if (nextSum > max) {
return;
}
currentElement.add(list.get(pos));
if (nextSum == max) {
for (Integer i : currentElement) {
System.out.print(i);
System.out.print(" ");
}
System.out.println();
} else if (nextSum < max && list.get(pos) < max - currentSum) {
// as array is sorted if current element is higher than the diff
// between currentSum and max there is no need to try with next
// element
for (int i=pos+1; i<list.size(); i++) {
sumNext(list, i, nextSum, max, currentElement);
}
}
currentElement.remove(list.get(pos));
}
}
將輸出:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.