关于递归的面试题
把一个数组里的数组合全部列出了 比如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 不是一直增加的吗 怎么会减少啊?多谢了
[解决办法]
括号里面是输出顺序:
4 123(3)--1234(4)
34 12(2)--3 124(5)--1243(6)
234 1(1)--24 13(7)
1234--134 2 23 14
124 3
123 4
[解决办法]
递归的过程可能要自己慢慢理解了,其实刚进入循环当i=0时,进行了下面的过程:
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
......剩下的过程和第一个节点差不多,感觉像二叉树的中序遍历?
[解决办法]
递归光用眼睛看感觉恨容易出错。还是要一步一步的用笔画出来。
先是一轮递归调用到最里面那层的出口,然后反向求解回来