I'm trying to use ArrayList in a recursive function. I'm trying to find the combinations of the array arr of size r. Like if I have an array
["A","B","C","D"]
I want to print :
A B C
A B D
A C D
B C D
But when I print my ArrayList in the recursive function it gives:
Call1 : ABC
Call2 : ABD
ABD
And so on. ie every time the previous contents of the ArrayList
are overwritten with the new content and the new content is also added to the end. Also in the Function calling the recursive function my ArrayList is not returned it just contains a list of Es.
In the function calling the recursive function I have something like
private static void combine(String[] arr, int r) {
String[] res = new String[r];
ArrayList<String[]> result = new ArrayList<String[]>();
doCombine(arr, res, 0, 0, r, result);
System.out.println("\nIn main" + result.size());
for (Object[] array : result) {
for (Object o : array)
System.out.print("item: " + o);
System.out.println();
}
}
// This recursive function finds combinations
private static void doCombine(String[] arr, String[] res, int currIndex,
int level, int r, ArrayList<String[]> result) {
if (level == r) {
printArray(res);
String[] inter = new String[r];
inter = res;
result.add(inter);
// Tryinh to see wht the array list has every time
for (Object[] array : result) {
for (Object o : array) {
System.out.print("item: " + o);
}
System.out.println();
}
inter = null;
return;
}
for (int i = currIndex; i < arr.length; i++) {
counter.add();
res[level] = arr[i];
doCombine(arr, res, i + 1, level + 1, r, result);
}
}
Please tell me what I am doing wrong.
Modify the code
String[] inter = new String[r];
inter = res;
result.add(inter);
to
String[] inter = new String[r];
int k=0;
for(String s:res){
inter[k] = s;
k++;
}
result.add(inter);
And the code work as Expected.
Output:
1
ABC
2
ABC
ABD
3
ABC
ABD
ACD
4
ABC
ABD
ACD
BCD
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.