在Java中整数分区整数、分区、Java

2023-09-11 22:46:00 作者:陌路人

下面是我的code做到这一点。它的工作原理为字符串重新presentation,而不是的ArrayList< ArrayList的<整数GT;> 一个

Here is my code to do this. It works for the string representation, but not the ArrayList<ArrayList<Integer>> one.

public static void partition(int n) {
    partition(n, n, "", new ArrayList<ArrayList<Integer>>(), new ArrayList<Integer>());
}
public static void partition(int n, int max, String temp, ArrayList<ArrayList<Integer>> master, ArrayList<Integer> holder) {
    if (n == 0) {
        ArrayList<Integer> temp1 = new ArrayList<Integer>();
        for(int i=0;i<=holder.size();i++)
        {
            temp1.add(holder.get(0));
            holder.remove(0);
        }
        master.add(temp1);
        System.out.println(temp);
    }

    for (int i = Math.min(max, n); i >= 1; i--) {
        holder.add(i);
        partition(n-i, i, temp + " " + i,master,holder);
    }
}

这是我做了有趣的业务temp1中的原因是,如果我只是添加温度掌握,在previous元素会改变(主机的所有元素将引用指向同一个地方),所以这我尝试了深刻的副本+明确的。

The reason that I am doing the funny business with temp1 is that if I were to just add temp to master, the previous elements would change (all elements in master would be references pointing to the same place) so this is my attempt at a deep copy + clear.

的字符串工作。为什么没有的ArrayList&LT; ArrayList的&LT;整数GT;&GT; ?我该如何解决?

The string works. Why doesn't the ArrayList<ArrayList<Integer>>? And how can I fix it?

该ArrayList(输出>是[5],[4,1],[3,2],[1,1],[2,2],[1,1,1],[1, 1,1,1]])

(Output of the ArrayList> is [[5], [4, 1], [3, 2], [1, 1], [2, 2], [1, 1, 1], [1, 1, 1, 1]])

推荐答案

正在混淆你的数组中的如果分支,你不应该这样做。请尝试以下操作:

You are mixing up your holder array inside the if branch which you shouldn't do. Try the following:

public static void partition(int n, int max, String temp, ArrayList<ArrayList<Integer>> master, ArrayList<Integer> holder) {
    if (n == 0) {
        ArrayList<Integer> temp1 = new ArrayList<Integer>();
        for (int i = 0; i < holder.size(); i++) {
            temp1.add(holder.get(i));
        }
        master.add(temp1);
        System.out.println(temp);
    }

    for (int i = Math.min(max, n); i >= 1; i--) {
        holder.add(i);
        partition(n - i, i, temp + " " + i, master, holder);
        holder.remove(holder.size() - 1);
    }
}