迅雷的一个笔试编程题

[size=medium][color=red]本人比较注重本题的效率问题,如果谁有可以改进的方法,希望大家能互相学习一下。[/color][/size]
题目:一个人能台阶,一次能登一级、二级或者三级台阶,假设有n级的台阶,请编写一个java的程序将各种的走法打印出来。

/*
* 总结:递归是解决一个问题的很好的方法,使问题的解决简单化,但是递归往往比较吃内存,当可以使用非递归的方式可以解决问题的时候,请
* 优先考虑非递归的方法;
* 以下的这个类只要添加一个main()方法就可以运行了,不过由于是用递归的,台阶大的话(最大只能是22),会发生内存的溢出,谁有更好的方法,希望能互相交流一下
*/

import java.util.ArrayList;
import java.util.List;
public class WalkStep2 {
private String excTime;
//保存结果的List
private List<List<Integer>> result=new ArrayList<List<Integer>>();
public WalkStep2(int leftStep){
long start=System.currentTimeMillis();
this.walkStep(new Node(leftStep));
long end=System.currentTimeMillis();
this.setExcTime((end-start)+" 毫秒(ms)");
}
public WalkStep2(){
this.walkStep(new Node(10));
}
public void add(List<Integer> aresult){
result.add(aresult);
}
public long getResultCount() {

return result.size();
}
public List<List<Integer>> getResult() {
return result;
}
public void setResult(List<List<Integer>> result) {
this.result = result;
}
public String getExcTime() {
return excTime;
}
public void setExcTime(String excTime) {
this.excTime = excTime;
}
//该类是一个节点的类
class Node{
private int leftStep;
private Node parent;
public Node(){}
public Node(int leftStep){
this.leftStep=leftStep;
}
public int getLeftStep() {
return leftStep;
}
public void setLeftStep(int leftStep) {
this.leftStep = leftStep;
}
public Node getParent() {
return parent;
}
public void setParent(Node parent) {
this.parent = parent;
}
}
public void walkStep(Node aNode){
//当剩余的台阶数为0的时候,就得到一种走法
if(aNode.getLeftStep()==0){
addKindOfResultToList(aNode);
}
walk(aNode);

}
//走台阶
private void walk(Node aNode) {
//只走一步的走法
if(aNode.getLeftStep()-1>=0) aWalk(aNode,1);
//只走两步的走法
if(aNode.getLeftStep()-2>=0) aWalk(aNode,2);

//只走三步的走法
if(aNode.getLeftStep()-3>=0) aWalk(aNode,3);
}
//将结果加到List链表中
private void addKindOfResultToList(Node aNode) {
List<Integer> list=new ArrayList<Integer>();
Node resultNode=aNode;
while( resultNode.getParent()!=null){
list.add(0,resultNode.getParent().getLeftStep()-resultNode.getLeftStep() );
resultNode=resultNode.getParent();
}
this.result.add(list);
}
//走下一步的方法
private void aWalk(Node aNode,int step) {
Node stepNode=new Node(aNode.getLeftStep()-step);
stepNode.setParent(aNode);
walkStep(stepNode);
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值