gpt4 book ai didi

java - 测试圆顶 : my solution works but I am only getting %50 right and not %100?

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:26:13 25 4
gpt4 key购买 nike

这是场景问题:

Frog 只能向前移动,但它可以步进 1 英寸长或跳跃 2 英寸长。 Frog 可以使用不同的步伐和跳跃组合来走相同的距离。

编写一个函数,计算 Frog 可以使用多少种不同的组合来走完给定的距离。

例如,3英寸的距离可以通过三种方式走完:步步步、步步跳和步步跳。

public class Frog{
public static int numberOfWays(int input) {

int counter = 2;

int x = 0;

for (int i = 1 ; i< input -1; i++ ){

x = i + counter;
counter = x;
}
if (input <3){
x = input;

}
return x;

}

public static void main(String[] args) {
System.out.println(numberOfWays(10));
}
}

这个解决方案只给我 %50 的权利不知道为什么它不是 %100,我用其他值测试它并返回正确的结果。

最佳答案

我认为递归是解决此类问题的好方法

public int numberOfCombinations(int distance) {
if (distance == 1) {
return 1; //step
} else if (distance == 2) {
return 2; // (step + step) or jump
} else {
return numberOfCombinations(distance - 1) + numberOfCombinations(distance - 2);
// we jumped or stepped into the current field
}
}

关于java - 测试圆顶 : my solution works but I am only getting %50 right and not %100?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32933200/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com