找到总和为给定数字的大小为N的组合

时间:2018-03-29 19:23:20

标签: java algorithm

给出数字C和数字N.我想找到总和为C的N个数字,这些数字的最高和最低之间的差值不应超过1。 例如:
鉴于这些 - > (C = 26,N = 7) - 我需要一种可以找到这些的算法 - > [4 4 4 4 4 3 3]
C = 11,N = 5 - [3 2 2 2 2]
C = 17,N = 4 - [5 4 4 4]
C = 10,N = 3 - [4 3 3]
C = 5,N = 2 - [3 2]
编辑:示例中有错误。 我这样做了:

    //N and C are declared above.
    int[] numbers = new int[N];
    int lowBound = C / N;
    int Modulo = C % N;
    for(int i = 0; i < numbers.length; i++) {
        numbers[i] = lowBound;
    }
    while(Modulo > 0) {
        for(int i = 0; i < numbers.length; i++) {

            if(Modulo < 1) break;
            numbers[i]++;
            Modulo--;
        }
     }

我也很抱歉。 我只是在寻找一个新手,我在这里很新。

1 个答案:

答案 0 :(得分:0)

从评论部分到答案框

原来你不需要循环,只需数学。

public class SolveCombination {
    public static List<Integer> solve(int c, int n) {
        int k = c / n;
        int rk = k + 1;
        int p = (c - (k * n));

        return Stream.concat(Stream.generate(() -> rk).limit(p), 
                             Stream.generate(() -> k).limit(n - p))
                     .collect(Collectors.toList());
    }
}

使用jshell运行示例

jshell> solve(26, 7)
$7 ==> [4, 4, 4, 4, 4, 3, 3]

jshell> solve(17, 4)
$8 ==> [5, 4, 4, 4]

jshell> solve(10, 3)
$9 ==> [4, 3, 3]

jshell> solve(5, 2)
$10 ==> [3, 2]

jshell> solve(11, 5)
$11 ==> [3, 2, 2, 2, 2]

jshell> solve(0, 5)
$12 ==> [0, 0, 0, 0, 0]

jshell> solve(1, 5)
$13 ==> [1, 0, 0, 0, 0]

jshell> solve(0, 0)
|  java.lang.ArithmeticException thrown: / by zero
|        at solve (#6:2)
|        at (#14:1)

jshell>