import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
String[][] datas = new String[][]{
new String[]{"1"},
new String[]{"2", "3"},
new String[]{"4", "5", "6"}
};
List<String> result = new ArrayList<>();
dfs(datas, 0, "", result);
System.out.println(result);
result.sort((o1, o2) -> {
int o1c = strCount(o1, '_');
int o2c = strCount(o2, '_');
if (o1c == o2c) {
return o1.compareTo(o2);
} else {
return o1c - o2c;
}
});
System.out.println(result);
}
public static int strCount(String source, char c) {
int ans = 0;
for (char sc : source.toCharArray()) {
if (sc == c) {
ans += 1;
}
}
return ans;
}
public static void dfs(String[][] datas, int line, String prefix, List<String> result) {
if (line >= datas.length) {
return;
}
// 将这行加入结果集
for (String str : datas[line]) {
if ("".equals(prefix)) {
dfs(datas, line + 1, str, result);
} else {
String newStr = prefix + "_" + str;
result.add(newStr);
dfs(datas, line + 1, newStr, result);
}
}
// 抛弃这行
dfs(datas, line + 1, prefix, result);
}
}
用的是dfs,
你给的样例打印顺序挺不合理的,看起来顺序是按照个数排序,但是遍历1开头2个结束后,再重新遍历1开头3个感觉是冗余的操作。所以我只能重新写了一个排序。但是我这个排序只是随便写写不作数的,还是需要你把问题补充完整