【问题标题】:Find all possible combinations of numbers to reach a given sum without a given set of numbers (Java) [closed]在没有给定数字集的情况下查找所有可能的数字组合以达到给定的总和(Java)[关闭]
【发布时间】:2021-08-24 05:25:44
【问题描述】:

如果没有给定的一组数字,您如何找到给定数字的所有整数(不包括负数)组合? 我想它最类似于寻找stars and bars 问题的解决方案。

例如,

  • 找出总和为 3 的 3 个数字的所有组合
  • 结果:(0,0,3) (0,1,2) (0,2,1) (0,3,0) (1,0,2) (1,1,1) (1, 2,0) (2,0,1) (2,1,0) (3,0,0)

我发现在 Python 中实现了类似的东西。在Java中可以做到这一点吗? General bars and stars

【问题讨论】:

  • (0,0,3) 和 (3,0,0) 是相同的组合。

标签: java algorithm math combinations


【解决方案1】:

您可以使用Stack 和递归找到n 正数与target 之和的所有可能组合

public class Test {
    private static final int n = 3;
    private static final int target = 3;

    public static void main(String[] args) {
        Stack<Integer> terms = new Stack<>();

        sums(terms, 0);
    }

    public static void sums(Stack<Integer> terms, int curSum) {
        if(terms.size() == n - 1) {
            terms.add(target - curSum);
            System.out.println(terms);
            terms.pop();
            return;
        }

        for(int i = 0; i <= target - curSum; i++) {
            terms.add(i);
            sums(terms, curSum + i);
            terms.pop();
        }
    }
}

输出

[0, 0, 3]
[0, 1, 2]
[0, 2, 1]
[0, 3, 0]
[1, 0, 2]
[1, 1, 1]
[1, 2, 0]
[2, 0, 1]
[2, 1, 0]
[3, 0, 0]

【讨论】:

    猜你喜欢
    • 2011-06-05
    • 1970-01-01
    • 2019-05-24
    • 2021-01-02
    • 1970-01-01
    • 2016-12-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多