【发布时间】:2019-04-23 15:42:21
【问题描述】:
给定一堆整数,请仅使用加号运算输出所有可能的数字的所有组合。
例如,
[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]
有人可以帮助我用 Java 实现这一点吗?
我已经尝试过,我认为它有效,但正在寻找其他解决方案。
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)));
}
【问题讨论】:
-
OP,您的帐户被黑客入侵了吗?看来您已经成为会员 5 年了,我想您知道 SO 的工作原理吗?
-
提示:从冒泡排序算法开始,但实际上不对列表进行排序。而是将元素的总和放入哈希集中
-
你“认为它有效”是什么意思?你有单元测试吗?
-
“寻找其他解决方案”不是一个很好的问题
-
我会使用递归方法来生成组合,并使用
TreeSet来存储排序输出的结果。