对于 Recursive Algorithm 中应当注意的
来源:互联网 发布:cctv怀旧源码新势力 编辑:程序博客网 时间:2024/05/18 01:58
在利用 Recursive Algorithm 进行树遍历时,需要注意:
1、当要修改诸如List类变量时,不要影响到后面的递归调用。
例如: [LeetCode]Permutations
private void helper(List<Integer> preList,List<Integer> remains,List<List<Integer>> ans){ //bound if(remains.size()==0){ List<Integer> list=new ArrayList<Integer>(preList); ans.add(list); return; } for(int i=0;i<remains.size();i++){ int n=remains.get(0); remains.remove(0); preList.add(n); helper(preList,remains,ans); preList.remove(preList.size()-1);//be careful remains.add(n); //be careful }}
当递归返回到本级时preList、remains
已经发生改变,如果没有13-14行就会出错。
2、当对值进行修改时,不要影响到后面的递归调用。
例如:[LeetCode]Unique Paths的DFS方法中
private void helper(int x,int y,int m,int n){ //base case if(x==m-1||y==n-1){ count++; return; } if(x<m-1) helper(x+1,y,m,n);//be careful if(y<n-1) helper(x,y+1,m,n);}
9行helper(x+1,y,m,n);
别写成helper(++x,y,m,n);
,它会影响11行helper(x,y+1,m,n);
的x
值。
0 0
- 对于 Recursive Algorithm 中应当注意的
- 上传文件中应当注意的细节
- 使用OpenCV中应当注意的几个问题
- 应当注意的细节
- 在gtk编译的过程中应当注意的。
- CPU卡发卡程序设计过程中应当注意的几个问题
- CPU卡发卡程序设计过程中应当注意的几个问题
- CPU卡发卡程序设计过程中应当注意的几个问题
- CPU卡发卡程序设计过程中应当注意的几个问题
- 上传文件中应当注意的细节(二)
- 汇编语言编程中应当注意的几大规范
- C#应当注意的地方
- 对于大表(千万级)建立索引时应当注意的事项及提高性能的手段
- [转]应当注意的生活坏习惯
- 运行javac应当注意的知识
- 对于%需要注意的
- VC++中应当注意对VC字符集的设置(非常好的一篇文章)
- UIViewController中loadView的用法(应当注意的几点)
- 笔记一java基本数据类型
- 实战CentOS系统部署Hadoop集群服务
- Fragment中嵌套Fragment问题
- java实现图片转ascii字符画
- 使用bootstrap-table遇到的一个坑
- 对于 Recursive Algorithm 中应当注意的
- C语言回调函数一个简单的例子
- 16位段和32位段
- release AAR的导出及自动拷贝
- Android源码编译出错No rule to make...
- kafka本机搭建、测试及常用命令
- noip2015 day2 t3
- Redis系列~安装(一)
- 使用 Github Pages 发布你的项目文档