为了打印所有路径,您需要传递您的历史记录。这意味着:
- 在每一点,添加当前条目,
- 递归调用您的函数,
- 再次删除最后一个条目。
你也可以
- 在每一点,复制迄今为止的历史,
- 将当前条目添加到副本中,
- 使用副本递归调用您的函数,
但前者占用的内存和时间更少。这有效:
import java.util.ArrayList;
public final class MatrixProblem {
private final int mx;
private final int my;
public MatrixProblem(int N) {
mx = N;
my = N;
}
public int countAndPrint() {
return numPathsTracing(0, 0, new ArrayList<>());
}
private int numPathsTracing(int x, int y, ArrayList<String> path) {
if(x > mx || y > my)
return 0;
else if(x == mx && y == my) {
StringBuilder pathString = new StringBuilder();
for(String previous : path) {
pathString.append(previous);
pathString.append(" -> ");
}
pathString.append(pathElement(x, y));
System.out.println(pathString);
return 1;
} else {
path.add(pathElement(x, y));
int ret = numPathsTracing(x+1, y, path) + numPathsTracing(x, y+1, path);
path.remove(path.size() - 1);
return ret;
}
}
private static String pathElement(int x, int y) {
return "(" + x + ", " + y + ")";
}
}
调用为:
int nPaths = new MatrixProblem(3).countAndPrint();
System.out.println("Total count is : " + nPaths);
输出:
(0, 0) -> (1, 0) -> (2, 0) -> (3, 0) -> (3, 1) -> (3, 2) -> (3, 3)
(0, 0) -> (1, 0) -> (2, 0) -> (2, 1) -> (3, 1) -> (3, 2) -> (3, 3)
(0, 0) -> (1, 0) -> (2, 0) -> (2, 1) -> (2, 2) -> (3, 2) -> (3, 3)
(0, 0) -> (1, 0) -> (2, 0) -> (2, 1) -> (2, 2) -> (2, 3) -> (3, 3)
(0, 0) -> (1, 0) -> (1, 1) -> (2, 1) -> (3, 1) -> (3, 2) -> (3, 3)
(0, 0) -> (1, 0) -> (1, 1) -> (2, 1) -> (2, 2) -> (3, 2) -> (3, 3)
(0, 0) -> (1, 0) -> (1, 1) -> (2, 1) -> (2, 2) -> (2, 3) -> (3, 3)
(0, 0) -> (1, 0) -> (1, 1) -> (1, 2) -> (2, 2) -> (3, 2) -> (3, 3)
(0, 0) -> (1, 0) -> (1, 1) -> (1, 2) -> (2, 2) -> (2, 3) -> (3, 3)
(0, 0) -> (1, 0) -> (1, 1) -> (1, 2) -> (1, 3) -> (2, 3) -> (3, 3)
(0, 0) -> (0, 1) -> (1, 1) -> (2, 1) -> (3, 1) -> (3, 2) -> (3, 3)
(0, 0) -> (0, 1) -> (1, 1) -> (2, 1) -> (2, 2) -> (3, 2) -> (3, 3)
(0, 0) -> (0, 1) -> (1, 1) -> (2, 1) -> (2, 2) -> (2, 3) -> (3, 3)
(0, 0) -> (0, 1) -> (1, 1) -> (1, 2) -> (2, 2) -> (3, 2) -> (3, 3)
(0, 0) -> (0, 1) -> (1, 1) -> (1, 2) -> (2, 2) -> (2, 3) -> (3, 3)
(0, 0) -> (0, 1) -> (1, 1) -> (1, 2) -> (1, 3) -> (2, 3) -> (3, 3)
(0, 0) -> (0, 1) -> (0, 2) -> (1, 2) -> (2, 2) -> (3, 2) -> (3, 3)
(0, 0) -> (0, 1) -> (0, 2) -> (1, 2) -> (2, 2) -> (2, 3) -> (3, 3)
(0, 0) -> (0, 1) -> (0, 2) -> (1, 2) -> (1, 3) -> (2, 3) -> (3, 3)
(0, 0) -> (0, 1) -> (0, 2) -> (0, 3) -> (1, 3) -> (2, 3) -> (3, 3)
Total count is : 20