我试图找到将字符串数组与两个元素组合的所有可能选项。让我们说,数组有两个元素{"我们","是"}。输出应该是:"我们" "是" "我们是" "我们是" 通过一些搜索,我可以管理这些代码:
public class Main {
public static void main(String[] args) {
String[] strings = {"we", "are"};
final int maxbit = 1 << strings.length;
for (int p = 0; p < maxbit; p++) {
String finalString = "";
for (int i = 0; i < strings.length; i++) {
if ((1 << i & p) > 0) {
finalString += strings[i] + " ";
}
}
System.out.println(finalString);
}
}
我的问题是,我错过了一个解决方案,输出如下:&#34;我们&#34; &#34;是&#34; &#34;我们是&#34;。 所以我错过了&#34;我们是&#34;选项,我是否需要使用递归来解决此问题,还是可以修改此代码以显示剩余选项?
更新:在答案的帮助下找到解决方案
public static void main(String[] args) {
String[] test = { "are", "we"};
language(test.length, test, "");
}
private static void language(final int n, final String[] syllables, final String currentWord) { // example of N = 3
if (n == 0) {
System.out.println(currentWord);
} else {
for (int i = 0; i < syllables.length; i++) {
if (currentWord.equals(syllables[i])){
language(n - 1, syllables, "" + syllables[i]);
}else{
language(n - 1, syllables, currentWord + syllables[i]);
}
}
}
}
答案 0 :(得分:0)
我查看了一段时间,并根据您的代码找到了两种方法:
这将打印出每个排列一次,并且不必包括所有单词:
public static void recPerm(String... input) {
recHelper(input, input.length, "");
}
private static void recHelper(String[] input, int length, String currentWord) {
if (currentWord != "")
System.out.println(currentWord);
for (int i = 0; i < input.length; i++) {
if (!currentWord.contains(input[i]))
recHelper(input, length - 1, currentWord + input[i]);
}
}
这将打印出每个排列一次,并且必须包括所有单词:
public static void maxRecPerm(String... input) {
maxRecHelper(input, input.length, "");
}
private static void maxRecHelper(String[] input, int length, String currentWord) {
if (length == 0)
System.out.println(currentWord);
for (int i = 0; i < input.length; i++) {
if (!currentWord.contains(input[i]))
maxRecHelper(input, length - 1, currentWord + input[i]);
}
}
答案 1 :(得分:0)
另一个例子
import java.util.Arrays;
public class HelloWorld{
public static void main(String[] args) {
String[] strings = {"we", "are"};
String str = Arrays.toString(strings);
System.out.println("Java String array to String = "+str.replace(",","").replace("[","").replace("]",""));
}
}