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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…