使用递归将偶数整数分离为2,4,6之和

时间:2019-03-18 17:27:44

标签: java recursion

我必须用Java编写一个递归方法,该方法使用递归将偶数整数分离为2,4,6之和,而同时不能连续有2个相同的数字。

例如n=8返回:

([2,4,2], [2,6], [6,2])

(where [2,2,2,2], [2,2,4], [4,2,2], [4,4] are not allowed as answers)

我正在寻找执行此操作的算法。目前,我在想为该方法提供两个参数,一个参数为int n,另一个为ArrayList<Integer>,以存储找到的分离方法。但是我很难想到可以做到这一点的算法。

public static ArrayList<Integer> subtractions(int n, ArrayList<Integer> integers){
    int sum = 0;
    for(Integer i:integers){
        sum += i;
    }
    if(n>2 && sum<n) {
        integers.add(n - 2);
        return subtractions(n - 2, integers);
    }
    integers.add(2);
    return integers;
}

这就是我现在所拥有的,但是在n=8的情况下只能给出一个答案,那就是[6,2]

有人可以给我一个起点吗?

2 个答案:

答案 0 :(得分:1)

您错过了整个级别的复杂性。您不应该处理整数列表,而应该处理整数列表。这个问题更多的是关于数据结构,而不是数学。我的示例解决方案:

public static List<List<Integer>> subtractions_recursive(int target, int exclude) {

    List<List<Integer>> solutions = new ArrayList<>();

    if (target == 0) { // base case for recursion
        List<Integer> empty = new ArrayList<>(); // ()
        solutions.add(empty); // (())
    } else {
        for (int i = 2; i <= 6 && target - i > -1; i += 2) {
            if (i == exclude) {
                continue;
            }

            List<List<Integer>> sub_solutions = subtractions_recursive(target - i, i); // ((4, 2), (6))

            for (List<Integer> sub_solution:sub_solutions) {
                sub_solution.add(0, i); // ((2, 4, 2), (2, 6))
            }

            solutions.addAll(sub_solutions);
        }
    }

    return solutions; // ((2, 4, 2), (2, 6), (6, 2))
}

public static List<List<Integer>> subtractions(int target) {
    return subtractions_recursive(target, 0);
}

答案 1 :(得分:0)

您的问题似乎与Subset Sum Problem有关。还有另一篇文章here。这两篇文章都可以很好地说明您将面对和开发解决方案的复杂性。您可能需要稍作修改,以删除连续具有相同编号序列的所有子集。 祝你好运