博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
深搜———ZOJ 1004:anagrams by stack
阅读量:4558 次
发布时间:2019-06-08

本文共 1392 字,大约阅读时间需要 4 分钟。

细节问题各种虐!!

其实就是简单的一个深搜

看成二叉树来理解:每个节点有两个枝:入栈和出栈。

剪枝操作:只有当栈顶元素和当前位置的目标字符相同时才出栈,否则就不出栈

dfs写三个参数:depth搜索深度,npush压栈数,npop出栈数

npush用于记录压栈数:主要判断当前压栈是否合理,以及要压入的元素在原串种的位置

npop用于记录出栈数:判断生成的目标串元素的位置

当npush==npop==目标串时,说明生成了一个可执行的操作串

注意输出操作串的时候一定要用depth参数来控制,因为在多次输入时string 的最大长度已经改变,只有利用depth才能确定该字符串的那一部分是当前所生成的。

贴代码!

# include
# include
# include
# include
using namespace std;string source;string target;char solution[200];char s[200];int top;void dfs(int depth, int npush, int npop){ if (npush == target.length() && npop == target.length()) { for (int i = 0; i < depth; i++) { cout << solution[i]<<" "; } cout << endl; return; } if (npush < target.length()) { s[top++] = source[npush]; solution[depth] = 'i'; dfs(depth + 1, npush + 1, npop); top--; } if (top > 0 && s[top - 1] == target[npop]) { solution[depth] = 'o'; char temp = s[top - 1]; top--; dfs(depth + 1, npush, npop + 1); s[top++] = temp; } return;}int main(){ while (cin>>source>>target) { top = 1; cout << "[" << endl; if (source.length() == target.length()) dfs(0,0,0); cout << "]" << endl; } return 0;}

 

转载于:https://www.cnblogs.com/digitalhermit/p/5037669.html

你可能感兴趣的文章
Android自定义UI
查看>>
spring boot整合quartz实现多个定时任务
查看>>
db powerdesign CDM、LDM、PDM、OOM的区别
查看>>
ISE和modelsim的配合
查看>>
通过用户模型,对数据库进行增删改查操作。
查看>>
群发邮件功能的完善
查看>>
gradle多项目构建及依赖
查看>>
linux, windows 文件传输的问题
查看>>
php:对象(object)数据类型实例详解
查看>>
关于java环境变量配置Javac命令无效问题
查看>>
常用的正则表达式
查看>>
Spring Boot使用@Async实现异步调用
查看>>
LeetCode 79. 单词搜索(Word Search)
查看>>
MySQL 多列索引优化小记
查看>>
J2SE核心开发实战(一)——认识J2SE
查看>>
gdbserver 远程调试问题:设置文件和so搜索路径
查看>>
SDK Build Tools revision (19.0.3) is too low for project Minimum required is 19.1.0
查看>>
推荐一个免费在线制作Banner的好地方
查看>>
javascript——select 标签的使用
查看>>
Python学习日志_2017/09/08
查看>>