Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
812 views
in Technique[技术] by (71.8m points)

algorithm - Integer Partition in Java

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

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.

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

Output of the ArrayList<ArrayList<Integer>> is:

[[5], [4, 1], [3, 2], [1, 1], [2, 2], [1, 1, 1], [1, 1, 1, 1]]
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...