我有一个唯一字符串数组,需要从中创建所有可能的具有相同长度的数组。
String[] str = {"Belgium", "France", "Germany"};
我们的目标是创建一个数组列表,这些数组在每个索引处都有上面数组中所有可能的值,
[Belgium, Belgium, Belgium]
[Belgium, Belgium, France]
[Belgium, Belgium, Germany]
[Belgium, France, Belgium]
[Belgium, France, France]
[Belgium, France, Germany]
[Belgium, Germany, Belgium]
[Belgium, Germany, France]
[Belgium, Germany, Germany]
[France, Belgium, Belgium]
....
[Germany, Germany, France]
[Germany, Germany, Germany]
我创建这个的代码如下
static List<String[]> getAllAllocations(String[] input){
List<String[]> result = new ArrayList<>();
if(input.length == 2){
for(int i = 0; i < 2; i++){
for(int j = 0; j < 2; j++){
result.add(new String[]{input[i], input[j]});
}
}
}
else if(input.length == 3){
for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
for(int k = 0; k < 3; k++){
result.add(new String[]{input[i], input[j], input[k]});
}
}
}
}
else if(input.length == 4){
for(int i = 0; i < 4; i++){
for(int j = 0; j < 4; j++){
for(int k = 0; k < 4; k++){
for(int m = 0; m < 4; m++){
result.add(new String[]{input[i], input[j], input[k], input[m]});
}
}
}
}
}
//else if(input.length == 5) similar code with 5 for loops
//else if(input.length == 6) similar code with 6 for loops
//else if(input.length == 7) similar code with 7 for loops
//else if(input.length == 8) similar code with 8 for loops
return result;
}
数组的长度在2到8之间。我如何动态地创建for循环,而不是链接if-else检查或任何其他方法,以一种比我上面做的更好的方式来实现这一点?
1条答案
按热度按时间tjrkku2a1#
递归解
迭代解法