鉴于这是家庭作业,因此我将尝试为您提供答案的背景。
解决此问题的关键是使用递归。
首先,假设您的数组中有两个项目。您可以删除第一个项目以得到您的第一个组合。将其余项添加到第一项将为您提供第二种组合。删除第二项将为您提供第三种组合。添加剩余的项目给您第四组合。如果有的
["air","bus"]话,将会是:
["air"]["air", "bus"]["bus"]["bus", "air"]
返回的方法可能类似于:
String[][] combinations(String[] strings)
需要注意的重要事项是,可以将包含单个字符串的数组传递给此方法,并且它可以返回其中包含单个字符串的数组的数组。
这个问题有点复杂,因为您必须保持字符串组合的计数,所以在我们解决这个问题之前,了解递归很重要。
想象一下,您想编写一个将两个数字相乘并将它们相乘的乘法方法,但是您只能使用加法和减法。您可以编写一个递归函数,将一个数字添加到自身,直到另一个数字达到退出条件,例如:
public int multiply(int value1, int value2) { if (value1 > 1) { int remaining = value1 - 1; return value2 + multiply(remaining, value2); } else { return value2; }}您可以对数组执行相同的操作,只不过当值命中时退出而不是
1在数组包含一项时退出,例如:
public String[][] combinations(String[] strings) { if (strings.length > 1) { ... } else { return new String[][]{strings}; }}由于Java API的原因,它
java.util.List比数组更易于使用,因此您需要执行以下操作:
public List<List<String>> combinations(List<String> strings) { if (strings.size()> 1) { ... } else { List<List<String>> result = new ArrayList<List<String>>(); result.add(strings); return result; }}现在,
...重要的是这一点。您需要保留一个列表列表,该列表将作为结果并在上进行迭代
strings。对于每个字符串,您可以将该字符串添加到结果中,然后需要创建一个减去当前字符串的子列表,您可以使用该子列表
combinations再次调用该方法,以遍历结果并将当前字符串添加到其中包含的每个列表。在代码中,它看起来像:
public List<List<String>> combinations(List<String> strings) { if (strings.size() > 1) { List<List<String>> result = new ArrayList<List<String>>(); for (String str : strings) { List<String> subStrings = new ArrayList<String>(strings); subStrings.remove(str); result.add(new ArrayList<String>(Arrays.asList(str))); for (List<String> combinations : combinations(subStrings)) { combinations.add(str); result.add(combinations); } } return result; } else { List<List<String>> result = new ArrayList<List<String>>(); result.add(new ArrayList<String>(strings)); return result; }}总之,您要做的是将字符串列表缩减为单个项目,然后将其与前面的项目组合在一起,以在线程返回调用堆栈时产生所有可能的组合。



