Integer section in Java

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

 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(ni, i, temp + " " + i,master,holder); } } 

The reason I am doing a funny business with temp1 is because if I just added temp for mastering, the previous elements would change (all elements in master would be links pointing to the same place), so this my attempt in deep copy + is clear.

The string is working. Why not ArrayList<ArrayList<Integer>> ? And how can I fix this?

(The output of ArrayList> is [[5], [4, 1], [3, 2], [1, 1], [2, 2], [1, 1, 1], [1, 1, 1, 1 ]])

0
java algorithm
source share
1 answer

You mix the 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); } } 
+2
source share

All Articles