给定一堆整数,请仅使用加号操作输出所有可能数字的所有组合

时间:2018-11-21 05:37:31

标签: java algorithm

给出一堆整数,请仅使用加号输出所有可能数字的所有组合。

例如

[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)));
}

1 个答案:

答案 0 :(得分:1)

如您在问题陈述中所述:

  

请使用加号输出所有可能数字的所有组合   仅限操作。

  • 解决方案的时间复杂度将保持指数级,即 O(2 N -1),因为我们必须尝试每个子序列的数组。

  • 因为您使用的是 TreeSet ,所以add的复杂度将增加log(n)的开销,而addAll()会增加{{1} },最坏的情况是O(m log (n))m是每棵树中元素的数量。参见此answer

  • 从技术上讲,这将使每一步的O(m log(n))复杂度加起来,使其为O(2 N -1)* O(m log(n) )。

  • 我建议您更好地使用 HashSet ,其中nadd()的平均性能为O(1)(可以提高到O (n)是否有碰撞,但通常不是这种情况。

  • 这样,复杂度仍为O(2 N -1),最后有contains()(非乘法)开销(如果您additional进行排序)将为wish,其中O(m log m)〜2 N -1。您也可以比较两种方法的运行时间。

代码:

m

输出:

import java.util.*;
public class CoinCombination {
        public List<Integer> getCoinSums(int[] coins) {
        Set<Integer> set = new HashSet<>();
        List<Integer> sums = new ArrayList<>();
        for (int coin : coins) {
            int size = sums.size(); 
            for(int j=0;j<size;++j){
                int new_sum = sums.get(j) + coin;
                if(!set.contains(new_sum)){
                    sums.add(new_sum);   
                    set.add(new_sum);
                }
            }
            if(!set.contains(coin)){
                sums.add(coin);
                set.add(coin);
            }
        }

        Collections.sort(sums);
        return sums;
    }

    public static void main(String[] args) {
        CoinCombination combination = new CoinCombination();
        int[][] coins = {
            {10,20},
            {1,2,3},
            {10, 20, 20, 50},
            {10, 20, 20, 50, 100}
        };
        for(int[] each_set_of_coins : coins){
            System.out.println(combination.getCoinSums(each_set_of_coins).toString());
        }        
    }
}