【发布时间】:2020-08-05 00:50:46
【问题描述】:
我想在 java 中创建一个算法,我可以在其中传递一个字符串列表,它会返回一个新列表,其中包含列表中所有可能的字符串组合。
例子:
String[] listWords = new String[] {
"windows",
"linux",
"mac",
"10",
"20"
};
我想通过传递返回所有可能组合的列表来调用方法。
combinations(listWords);
这是我想要的结果:
windows,linux,mac,10,20,windowslinux,linuxwindows,windowsmac,windows10,10windows,windows20,20windows,windowslinuxmac1020,windowsmaclinux20,mac10,mac20,20mac,20mac10,windowsmac,macwindows...
我试过了:
public String[][] combinations (String[] ports) {
List<String[]> combinationList = new ArrayList<String[]>();
for ( long i = 1; i < Math.pow(2, ports.length); i++ ) {
List<String> portList = new ArrayList<String>();
for ( int j = 0; j < ports.length; j++ ) {
if ( (i & (long) Math.pow(2, j)) > 0 ) {
portList.add(ports[j]);
}
}
combinationList.add(portList.toArray(new String[0]));
}
return combinationList.toArray(new String[0][0]);
}
但这会返回:
这不是我想要的。结果必须是:
列表:[windows, linux, windowslinux, linuxwindows, windows10, 10windowsmaclinux...]
在java中可以做到这一点吗?谢谢谁能帮忙:)
【问题讨论】:
-
顺便给个提示:
List.of( "windows", "linux", "mac", "10", "20" )
标签: java arrays string combinations