• 主页

# [讨论]关于递归的一点想法

maksim_wei CTO  2005-09-06 02:00:04

// 先定义递归所需接口
public interface Recursive
{
public void recursiveForward(Object init);
public Object recursiveStep(Object in);
public Object recursiveReturn();
public boolean exitCondition();
}

// 再定义Command模式类
public class RecursiveCommand
{
private Recursive m_rec;
public RecursiveCommand(Recursive rec)
{
m_rec = rec;
}
public Object doCommand(Object init)
{
if (m_rec.exitCondition())
return null;
else
{
m_rec.recursiveForward(init);
init = m_rec.recursiveStep(init);
doCommand(init);
return m_rec.recursiveReturn();
}
}
}

public class Factor implements Recursive
{
private int m_factor;
private int result = 1;

public Factor(int factor)
{
m_factor = factor;
}

public void recursiveForward(Object in)
{
result *= ((Integer)in).intValue();
m_factor--;
}

public Object recursiveStep(Object in)
{
int inValue = ((Integer)in).intValue();
return new Integer(--inValue);
}

public boolean exitCondition()
{
if (m_factor <= 0)
return true;
else
return false;
}

public Object recursiveReturn()
{
return new Integer(result);
}
}

public class SystemEntrance
{
public static void main(String[] args)
{
SystemEntrance se = new SystemEntrance();
Factor fac = new Factor(6);
RecursiveCommand rc = new RecursiveCommand(fac);

Object objResult = rc.doCommand(new Integer(6));

System.out.println(objResult.toString());
}
}
...全文
154 点赞 收藏 9

9 条回复

qinzaoxiaolan 2005-09-07
up

sjjf 2005-09-07

1. 如何计算 Fibonacci 数列？
2. 如何计算 算法复杂度， 在o(n3) 下面 系统的开销可能会是多少，以 n = 1k 估算一下,当中的内存变量，参数 and so on？

LongxiaoZeng2001 2005-09-07

maksim_wei 2005-09-07

maksim_wei 2005-09-07
ft,难道是这个题目没有讨论的意义？为什么连一块板砖都没有？

saiche05 2005-09-07

ing

maksim_wei 2005-09-07

maksim_wei 2005-09-06

zebra007 2005-09-06

Java SE

6.1w+

Java 2 Standard Edition