您的位置:首页 > 理论基础 > 数据结构算法

数据结构之递归

2013-11-26 23:12 316 查看
在这篇文章里,我们主要讨论和递归相关的话题。递归是数据结构中解决复杂问题时非常有效的一种思考方式,对于一个复杂的问题,我们可以从中抽取一个可以通过迭代方式解决的子问题,而子问题是一个容易解决的问题。在使用递归时,有两个问题需要注意:1)抽取递归体;2)确定递归边界条件以及处理方式。

  下面我们来看相关的题目。

斐波那契数列 我想这应该是最常见的递归的例子了,我们可以使用递归和非递归两种方式来实现它。 首先来看非递归的方式:
求硬币组合

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


最后,欢迎大家提出更多和递归相关的面试题目,我们可以一起讨论。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: