数据结构之递归
2013-11-26 23:12
316 查看
在这篇文章里,我们主要讨论和递归相关的话题。递归是数据结构中解决复杂问题时非常有效的一种思考方式,对于一个复杂的问题,我们可以从中抽取一个可以通过迭代方式解决的子问题,而子问题是一个容易解决的问题。在使用递归时,有两个问题需要注意:1)抽取递归体;2)确定递归边界条件以及处理方式。
下面我们来看相关的题目。
斐波那契数列 我想这应该是最常见的递归的例子了,我们可以使用递归和非递归两种方式来实现它。 首先来看非递归的方式:
求硬币组合
执行结果(假设N=25)
最后,欢迎大家提出更多和递归相关的面试题目,我们可以一起讨论。
下面我们来看相关的题目。
斐波那契数列 我想这应该是最常见的递归的例子了,我们可以使用递归和非递归两种方式来实现它。 首先来看非递归的方式:
求硬币组合
public static void combine(int n) { ArrayList<Integer> list = new ArrayList<Integer>(); ArrayList<ArrayList<Integer>> all = new ArrayList<ArrayList<Integer>>(); combinRecursive(n, list, all); } private static void combinRecursive(int n, ArrayList<Integer> list, ArrayList<ArrayList<Integer>> all) { if (n == 0) { Collections.sort(list); boolean bExist = false; for(ArrayList<Integer> temp : all) { if (temp.size() == list.size()) { int j = 0; for(int i = 0; i < temp.size(); i++) { if (temp.get(i) != list.get(i)) break; j++; } if (j == temp.size()) { bExist = true; break; } } } if (!bExist) { all.add(list); StringBuffer sb = new StringBuffer(); for(int value1 : list) sb.append(value1).append("->"); System.out.println(sb.substring(0, sb.length() - 2)); } } if (n >= 25) { ArrayList<Integer> temp = (ArrayList<Integer>)list.clone(); temp.add(25); combinRecursive(n - 25, temp, all); } if (n >= 10) { ArrayList<Integer> temp = (ArrayList<Integer>)list.clone(); temp.add(10); combinRecursive(n - 10, temp, all); } if (n >= 5) { ArrayList<Integer> temp = (ArrayList<Integer>)list.clone(); temp.add(5); combinRecursive(n - 5, temp, all); } if (n >= 1) { ArrayList<Integer> temp = (ArrayList<Integer>)list.clone(); temp.add(1); combinRecursive(n - 1, temp, all); } }
执行结果(假设N=25)
25 5->10->10 1->1->1->1->1->10->10 5->5->5->10 1->1->1->1->1->5->5->10 1->1->1->1->1->1->1->1->1->1->5->10 1->1->1->1->1->1->1->1->1->1->1->1->1->1->1->10 5->5->5->5->5 1->1->1->1->1->5->5->5->5 1->1->1->1->1->1->1->1->1->1->5->5->5 1->1->1->1->1->1->1->1->1->1->1->1->1->1->1->5->5 1->1->1->1->1->1->1->1->1->1->1->1->1->1->1->1->1->1->1->1->5 1->1->1->1->1->1->1->1->1->1->1->1->1->1->1->1->1->1->1->1->1->1->1->1->1
最后,欢迎大家提出更多和递归相关的面试题目,我们可以一起讨论。
相关文章推荐
- 拓扑排序
- 邻接矩阵实现的拓扑排序
- 邻接表实现的拓扑排序
- 数据结构与算法实验题 11.3 最小权语言问题
- 数据结构与算法实验题 11.3 最小权语言问题
- 数据结构算法(1) 最小路径
- 【数据结构】第4周 二叉树基础
- 数据结构的概述
- CGAL几何库 半边网格数据结构 模板类 设计核心思想
- 数据结构 实验五 查找
- 【玩转cocos2d-x之二十六】数据结构CCDictionary
- nyoj128 前缀式求值(栈---递归---数据结构)
- 数据结构B树
- 数据结构与算法实验题 数据结构与算法实验题 10 .2 小明解题报告
- sicily 数据结构 1014. Translation
- 最短路径(有向图)
- 程序员面试题精选100题(04)-二元树中和为某一值的所有路径[数据结构]
- 数据结构与算法实验题 10.1 神谕者
- 数据结构与算法实验题 10.1 神谕者
- LRU Cache数据结构简介