When recursing with Lists in Java, I frequently end up allocating and copying lists many many times. For example, I want to generate a List<List<Integer>>
of all possible Integer sequences where:
- Every number is between 1 and 9
- Every number is greater or equal to the number before it
- A number can appear between 0 and 3 times in a row.
For example, [1,1,1,2,2,2,3,3,3,4,4,4,5,5,5,6,6,6,7,7,7,8,8,8,9,9,9]
is the largest sequence. I have a recursive method that does this:
static void recurse(List<List<Integer>> addto, List<Integer> prev, int n){
if(n>=10)
addto.add(prev);
else{
for(int i=0; i<=3; i++){
List<Integer> newlist = new ArrayList<Integer>(prev);
for(int k=0; k<i; k++){
newlist.add(n);
}
recurse(addto, newlist, n+1);
}
}
}
What happens here is that I'm copying the entire prev
list 3 times every recursion. I need to do this in order to concatenate stuff to my list and pass it on to the next iteration. This is very slow (2 seconds). A less elegent version using 10 nested loops ran much faster because it did not have to copy so many lists. What's the 'proper' way to do this?
By the way this is not homework, but related to one of the USACO problems.