import java.util.ArrayList;
import java.util.Arrays;
public class SumSet {
static void sum_up_recursive(ArrayList<Integer> numbers, int target, ArrayList<Integer> partial) {
int s = 0;
for (int x : partial) {
s += x;
}
if (s == target) {
System.out.println("sum(" + Arrays.toString(partial.toArray()) + ")=" + target);
}
else if (s >= target) {
return;
}
for (int i = 0; i < numbers.size(); i++) {
ArrayList<Integer> remaining = new ArrayList<>();
int n = numbers.get(i);
for (int j = i + 1; j < numbers.size(); j++) {
remaining.add(numbers.get(j));
}
ArrayList<Integer> partial_rec = new ArrayList<>(partial);
partial_rec.add(n);
sum_up_recursive(remaining, target, partial_rec);
}
}
static void sum_up(ArrayList<Integer> numbers, int target) {
sum_up_recursive(numbers, target, new ArrayList<>());
}
public static void main(String[] args) {
Integer[] numbers = { 5, 5, 10, 15 };
int target = 15;
sum_up(new ArrayList<>(Arrays.asList(numbers)), target);
}
}
The current output is:
sum([5, 10])=15
sum([5, 10])=15
sum([15])=15
I am trying to figure out how to get the output to print the position of the array:
sum([3]) = 15
sum([0,3)] = 15
sum([1,3)]=15
If I understand your question correctly you want to print the position in the original list, right?
In that case I'd suggest you use a custom element type, eg something like this:
class PositionalElement {
final int position;
final int value;
public PositionalElement( int pos, int val ) {
position = pos;
value = val;
}
}
and
int[] numbers = new int[] {5,5,10,15};
List<PositionalElement> elements = new ArrayList<>();
for( int i = 0; i < numbers.length; i++ ) {
elements.add( new PositionalElement( i, numbers[i] ) );
}
That way, when printing your output you're free to either use value
and/or position
of each element.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.