Found Solution
Finding all possible combinations of numbers to reach a given sum
Question
In the above solution, it is possible to get all the combinations without repeating the same number using given set of numbers to sum up to the given value.
How to manipulate the algorithm below to get all possible combinations including repetitive numbers to sum up to the given value?
import java.util.ArrayList;
import java.util.Arrays;
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);
if (s >= target)
return;
for (int i = 0; i < numbers.size(); i++)
{
ArrayList<Integer> remaining = new ArrayList<Integer>();
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<Integer>(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<Integer>());
}
public static void main(String args[])
{
Integer[] numbers = { 3, 9, 8, 4, 5, 7, 10 };
int target = 15;
sum_up(new ArrayList<Integer>(Arrays.asList(numbers)), target);
}
}
And output should not contain Permutations and only Combinations.
Example
15 can be summed up by 3 + 3 + 3 + 3 + 3
and 9 + 3 + 3
. However output should only contain one of following, 9 + 3 + 3
or 3 + 9 + 3
or 3 + 3 + 9