I was asked about this program in an interview. The task is given an integer array as input and another number say target, find all possible combinations in array that sum up to given target.
Example:
array = [1,2,1,1,1]
target = 3
expected result : [1,2],[1,1,1],[2,1],[2,1]
I have come up with below code:
public static void main(String args[]) {
Integer[] numbers = { 1, 2, 1, 1, 1 };
int target = 3;
process(numbers, target);
}
private static void process(Integer[] numbers, int target) {
for (int i = 0; i < numbers.length; i++) {
int sum = 0;
for (int j = i; j < numbers.length; j++) {
sum += numbers[j];
if (sum == target) {
for (int k = i; k <= j; k++) {
System.out.print(numbers[k] + " ");
}
System.out.println();
}
}
}
}
But this code only prints 3 combinations : [1 2], [2 1], [1 1 1]
What is the correct way to do this? Is there any other better solution.