java - 为什么删除 StringBuilder 语法错误中的最后一个字符?
问题描述
public ArrayList<String> printPaths(char[][] board){
ArrayList<String> out = new ArrayList<>();
StringBuilder sb = new StringBuilder();
search(0,0,board,sb,out);
return out;
}
public void search(int i, int j, char[][] board, StringBuilder sb, ArrayList<String> out){
int rows = board.length;
int cols = board[0].length;
if(i > rows-1 || j > cols-1) return;
sb.append(board[i][j]); // Mark
if(i == rows-1 && j == cols-1){
out.add(sb.toString());
sb.deleteCharAt(sb.length()-1);
return;
}
search(i+1,j,board,sb,out); // Search Down
search(i,j+1,board,sb,out); // Search Right
sb.deleteCharAt(sb.length()-1); // Un-Mark
}
在段落之间放置换行符 在末尾添加两个空格 ► 修复语法或拼写错误 ► 澄清含义而不更改它 ► 纠正小错误 ► 添加相关资源或链接 ► 始终尊重原作者 ► 修复语法或拼写错误 ► 澄清含义而不更改它 ► 纠正小错误 ► 添加相关资源或链接 ► 永远尊重原作者
解决方案
这是回溯逻辑。以这种方式查看这些说明(添加评论):
sb.append(board[i][j]); // Mark
if(i == rows-1 && j == cols-1){
out.add(sb.toString());
/*
Here, you reached the bottom-right element of the matrix.
You can no longer go down or right, so you perform a backtracking
by deleting the last element read.
*/
sb.deleteCharAt(sb.length()-1);
return;
}
search(i+1,j,board,sb,out); // Search Down
search(i,j+1,board,sb,out); // Search Right
/*
Here, you exhausted the elements on bottom and right
(because you just returned from the two search() calls). Perform a backtracking by
removing the last element (which is a dead end) before returning to the calling
recursion step:
*/
sb.deleteCharAt(sb.length()-1); // Un-Mark
推荐阅读
- php - 如何在 Jquery、PHP 和 AJax 中用多边形注释图像?
- spring-integration - Spring-Integration Webflux 异常处理
- ios - 将协议与关联对象绑定 - 使用 Swift 进行面向协议的编程
- ffmpeg - 为什么这条 ffmpeg 行会使 image_0 变灰?
- javascript - 有人知道如何解决此错误:无法在未安装的组件上调用 setState (or forceUpdate) ....?
- mysql - 未找到记录时出现错误 #2014 - 命令不同步;你现在不能运行这个命令
- docker - Docker 提交 - 不保留新设置?
- java - JavaFX 在后台线程中加载系统图标
- python - Python list to make double qoute around string and pass to api
- django - Django 代码更改不会反映在生产服务器上