I have this code…that does just about exactly what I need it to. It searches a predefined array of ints for two ints that sum up to a target int. However, when putting values into the vector, rather than placing them within cells, it places all the values together.
i.e. for int array[50,40,30,20,10] and target 50, rather than returning [[50][40,10][30,20]…etc.], it prints [[50,40,10,30,20…etc.]] How can I fix this?
public Vector<Vector<Integer>> subsetSum(int[] array, int target) {
//creates vectors, adds inner vector to another vector
outer = new Vector<Vector<Integer>>();
inner = new Vector<Integer>();
outer.add(inner);
for (int k = 0; k < array.length; k++) {
for (int l = 1; l < array.length; l++) {
int sum = array[k]+array[l]; //sum of l and k
if (sum == target) {
//add l,k to vector
inner.add(array[l]);
inner.add(array[k]);
//prints l and k if their sum equals target
System.out.println(array[l]+"+"+array[k]+"="+target);
}
else {
System.out.print("");
}
}
//if k is the target, display
if (array[k] == target) {
//add k to vector
inner.add(array[k]);
//prints if int equals target
System.out.println(array[k]+"="+target);
}
}
//return combinations that add up to target in vector form
return outer;
}
You’re only ever adding a single vector to
outer. Isn’t it the case that if you find a pair that add up to the required sum, you want them in a distinct vector? So, you need to create a new “inner” vector when that happens, and add it toouter.Remove these lines:
Change:
And:
Finally, consider making
innerandouterinto local variables.