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.
You can do something like this using backtracking:
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> result = new ArrayList<>();
List<Integer> temp = new ArrayList<>();
Arrays.sort(candidates);
int start = 0;
backtrack(candidates, target, start, result, temp);
return result;
}
public void backtrack(int[] candidates, int remaining, int start, List<List<Integer>> result, List<Integer> temp) {
if(remaining == 0) {
result.add(new ArrayList<>(temp));
return;
}
if(remaining < 0) { return; }
for(int i = start; i < candidates.length; i++) {
temp.add(candidates[i]);
backtrack(candidates, remaining - candidates[i], i, result, temp);
temp.remove(temp.size() - 1);
}
}
You can read more about backtracking and similar approaches.
This is an excellent candidate for using recursion:
public static void main(String args[]) {
Integer[] numbers = { 1, 2, 1, 1, 1 };
int target = 3;
for(int i = 0; i < numbers.length; i++) {
recurseAdd(i, numbers, new ArrayList<Integer>(), 0, target);
}
}
private static void recurseAdd(int currentIndex, Integer[] numbers, List<Integer> usedNumbers, int sum, int target) {
if (currentIndex >= numbers.length) {
return;
}
sum = sum + numbers[currentIndex];
usedNumbers.add(numbers[currentIndex]);
if (sum == target) {
System.out.println(usedNumbers);
return;
}
if (sum > target) {
return;
}
for (int i = currentIndex + 1; i < numbers.length; i++) {
recurseAdd(i, numbers, new ArrayList<>(usedNumbers), sum, target);
}
}
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.