I want to store the data variables (String[]) to variable results in ArrayList, and then the final results of recursive function is ArrayList results. in this case return [[ani,budi],[ani,cici],[budi,cici]]. Anyone can help me?
static void combinationUtil(String arr[], String data[], int start,
int end, int index, int r, ArrayList<String[]> results)
{
if (index == r){
results.add(data);
System.out.println(Arrays.toString(data));
return;
}
for (int i=start; i<=end && end-i+1 >= r-index; i++){
data[index] = arr[i];
combinationUtil(arr, data, i+1, end, index+1, r, results);
}
}
public static void main (String[] args) {
String arr[] = {"ani", "budi", "cici"};
int r = 2;
int n = arr.length;
String data[] = new String[r];
ArrayList<String[]> results = new ArrayList<String[]>();
combinationUtil(arr, data, 0, n-1, 0, r, results);
}
Update the line of adding the array to the list and make a copy, because the saved array is changing in other iterations
results.add(Arrays.copyOf(data, data.length));
, To be like this:
static void combinationUtil(String arr[], String data[], int start, int end, int index, int r,
ArrayList<String[]> results) {
if (index == r) {
results.add(Arrays.copyOf(data, data.length));
return;
}
for (int i = start; i <= end; i++) {
data[index] = arr[i];
combinationUtil(arr, data, i + 1, end, index + 1, r, results);
}
}
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.