把一个数组里的数组合全部列出了 比如1 2 列出来为 1,2 ,12,21, 代码是:
public static void main(String[] args) throws Exception {
String[] array = new String[] {
"1", "2", "3", "4"
};
listAll(Arrays.asList(array), "");
}
public static void listAll(List candidate, String prefix) {
// if (candidate.isEmpty()) {
System.out.println(prefix);
// }
for (int i = 0; i < candidate.size(); i++) {
List temp = new LinkedList(candidate);
listAll(temp, prefix + temp.remove(i));
}
}
=====输出=====
1
12
123
1234
124
1243
13
132
1324
134
1342
14
142
1423
143
1432
2
21
213
2134
214
2143
23
231
2314
234
2341
24
241
2413
243
2431
3
31
312
3124
314
3142
32
321
3214
324
3241
34
341
3412
342
3421
4
41
412
4123
413
4132
42
421
4213
423
4231
43
431
4312
432
4321 有个问题百思不得其解,就是从1234怎么变为124的?根据prefix + temp.remove(i), prefix 不是一直增加的吗 怎么会减少啊?多谢了
public static void main(String[] args) throws Exception {
String[] array = new String[] {
"1", "2", "3", "4"
};
listAll(Arrays.asList(array), "");
}
public static void listAll(List candidate, String prefix) {
// if (candidate.isEmpty()) {
System.out.println(prefix);
// }
for (int i = 0; i < candidate.size(); i++) {
List temp = new LinkedList(candidate);
listAll(temp, prefix + temp.remove(i));
}
}
=====输出=====
1
12
123
1234
124
1243
13
132
1324
134
1342
14
142
1423
143
1432
2
21
213
2134
214
2143
23
231
2314
234
2341
24
241
2413
243
2431
3
31
312
3124
314
3142
32
321
3214
324
3241
34
341
3412
342
3421
4
41
412
4123
413
4132
42
421
4213
423
4231
43
431
4312
432
4321 有个问题百思不得其解,就是从1234怎么变为124的?根据prefix + temp.remove(i), prefix 不是一直增加的吗 怎么会减少啊?多谢了
这个输出顺序是按什么规律得出的 看不明白啊
listAll(234, 1)(此时print:1)
||
\/
listAll(34, 12)(此时print:12) listAll(24, 13) listAll(23, 14)
||
\/
listAll(4, 123)(print:123) listAll(3, 124)(print:124)
|| ||
\/ \/
print:1234 print:1243
所以是:
print:1
print:12
print:123
print:1234
print:124
print:1243
print:13
......剩下的过程和第一个节点差不多,感觉像二叉树的中序遍历?