[英]How to store recursive function value in array JAVA
I want to store the data variables (String[]) to variable results in ArrayList, and then the final results of recursive function is ArrayList results.我想将数据变量(String[])存储到ArrayList中的变量结果中,然后递归function的最终结果就是ArrayList结果。 in this case return [[ani,budi],[ani,cici],[budi,cici]].
在这种情况下返回 [[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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.