Given a bunch of integer numbers, please output all combination of all possible numbers by using plus operation only.
For example,
[10, 20] => [10, 20, 30]
[1, 2, 3] => [1, 2, 3, 4, 5, 6]
[10, 20, 20, 50] => [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
Could someone help me with a method to do that in Java ?
I have made tries and I think it works, but looking for other solutions.
public int[] getCoins2(int[] coins) {
Set<Integer> result = new TreeSet<>();
for (int coin : coins) {
result.addAll(result.stream().map(value -> value + coin).collect(Collectors.toSet()));
result.add(coin);
}
return toInt(result);
}
public int[] toInt(Set<Integer> set) {
int[] a = new int[set.size()];
int i = 0;
for (Integer val : set) {
a[i++] = val;
}
return a;
}
public static void main(String[] args) {
CoinCombination combination = new CoinCombination();
int[] coins = {10, 20, 20, 50, 100};
System.out.println(Arrays.toString(combination.getCoins2(coins)));
}