[英]how to store array in a recursive function?
I have a permutation recursive array which works fine but I need to store the result not just print them out,I have to store each print out in a separate array or the whole in one array 我有一个排列递归数组,它可以正常工作,但我需要存储结果而不只是打印出来,我必须将每个打印结果存储在单独的数组中或整个存储在一个数组中
here is the original: 这是原件:
public static void Permute(String soFar, String rest)
{
if (rest.isEmpty())
{
System.out.println(soFar);
}
else
{
for (int i =0; i < rest.length(); i++)
{
String next = soFar + rest.charAt(i);
String remaining = rest.substring(0,i) + rest.substring(i+1);
Permute(next,remaining);
}
}
}
and I changed it but the problem is that return arr is not proper in there I should do something else because the arr would become empty because other recursive function would be called and I don't want it 我更改了它,但是问题是返回的arr不正确,我应该做些其他的事情,因为arr会变为空,因为会调用其他递归函数,但我不想要它
public static String Permute(String soFar, String rest,String arr)
{
if (rest.isEmpty())
{
// System.out.println(soFar);
arr+=soFar;
}
else
{
for (int i =0; i < rest.length(); i++)
{
String next = soFar + rest.charAt(i);
String remaining = rest.substring(0,i) + rest.substring(i+1);
Permute(next,remaining,arr);
}
}
return arr;
}
One way; 单程;
List<String> myList = new ArrayList<String>();
List<String> myList = new ArrayList<String>();
System.out.println(soFar);
System.out.println(soFar);
with myList.add(soFar);
myList.add(soFar);
String[] arr = (String[]) myList.toArray();
String[] arr = (String[]) myList.toArray();
Change your arr
parameter to be a List. 将您的
arr
参数更改为列表。 Then instead of the println() just keep adding to this List. 然后继续添加到此列表中,而不是println()。 Also, when you call permute for the first time, make sure you pass in an allocated List.
同样,当您第一次调用置换时,请确保您传递了分配的列表。 Like so:
像这样:
public void ParentFunction()
{
List<String> results = new ArrayList<String>();
Permute(..., ..., results);
// Now you have all results inside "results" variable.
}
public static void Permute(String soFar, String rest, List<String> results)
{
if (rest.isEmpty())
{
//System.out.println(soFar);
results.add(soFar); // ADD TO RESULT LIST
}
else
{
for (int i = 0; i < rest.length(); i++)
{
String next = soFar + rest.charAt(i);
String remaining = rest.substring(0, i) + rest.substring(i + 1);
Permute(next, remaining, results);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.