我被困在这段代码中:
问题:一个孩子可以一次以 1,2 或 3 级的步数跳 n 级楼梯。给定 n 的值,打印出他可以爬楼梯的所有排列。
这是我的代码:
public class HoppingLad
{
int count;
void hop(int n,int present)
{
if(n==present)
{
count++;
System.out.println("\nFinished type "+count+" climbing.\n");
}
else
{
if((n-present)>=1)
{
System.out.print("\nClimbed 1 step.\nReached "+(present+1)+" ");
hop(n,present+1);
}
if((n-present)>=2)
{
System.out.print("\nClimbed 2 step. \nReached "+(present+2)+" ");
hop(n,present+2);
}
if((n-present)>=3)
{
System.out.print("\nClimbed 3 step. \nReached "+(present+3)+" ");
hop(n,present+3);
}
}
}
public static void main(String [] args)
{
HoppingLad hl=new HoppingLad();
hl.hop(3, 0);
System.out.println("There are "+hl.count+" ways to climb.");
}
}
输出是:
Climbed 1 step.
Reached 1
Climbed 1 step.
Reached 2
Climbed 1 step.
Reached 3
Finished type 1 climbing.
Climbed 2 step.
Reached 3
Finished type 2 climbing.
Climbed 2 step.
Reached 2
Climbed 1 step.
Reached 3
Finished type 3 climbing.
Climbed 3 step.
Reached 3
Finished type 4 climbing.
There are 4 ways to climb.
我得到的输出部分正确,部分不完整。爬楼梯的方法数量是正确的,但正如你所注意到的,
爬过 2
达到 3
部分输出即将到来
攀爬 1
到达 1
部分在它之前。我已经绘制了递归树,该树甚至表明输出中不存在第一部分。
然而,用户必须从地面得到指导。我尝试了很多东西,但无济于事。谁能帮我解决这个问题?