我长期坚持这个问题。
问题
你正走上一个有x步的阶梯。如果一次只能采取1步或2步,找到所有组合以进入此阶梯。
此问题几乎没有限制。 没有循环,没有数组,必须使用递归。
这是我到目前为止所做的。
public static String climb(int remainingSteps, String combo) {
// terminator
if (remainingSteps == 0) {
combo = combo + "";
}
// recursion
else {
if (remainingSteps == 1) {
combo = combo + "1, ";
} else { // remainingSteps is greater than or equal to 2
int step = 1; // this part isn't right
switch (step) {
case 1:
combo = waysToClimbHelper(remainingSteps - step, combo) + "1, ";
break;
case 2:
combo = waysToClimbHelper(remainingSteps - step, combo) + "2, ";
break;
}
}
}
return combo;
}
我需要它来展示爬梯子的所有独特方式,所以说梯子有3个步骤,它应该显示
1, 1, 1
2, 1
1,2
但是,正如您从我的代码中看到的那样,我将步长设置为1,因此它一次只能采取一步。我无法巧妙地改变步长,以便程序能够显示所有独特的路径。
答案 0 :(得分:0)
我不明白为什么你需要将步长设置为1.它应该类似于:
climb(String steps, int remainingSteps) {
if (remaiingSteps == 0) {
print steps
} else if (remainingSteps == 1) {
print steps + "1"
} else {
// either climb one step this time
climb(steps + "1 ", remainingSteps -1);
// or client 2 steps this time
climb(steps + "2 ", remainingSteps -2 );
}
}
如果您了解上述递归,那么获取所有唯一路径应该不会有任何困难。更直观的递归(对于现实生活,您可能希望将结果List作为参数传递而不是返回)。伪代码:
List<String> climb(String steps, int remainingSteps) {
if (remaingSteps == 0) {
return [steps]
} else if (remainingSteps == 1) {
return [steps + "1 "]
} else {
// combine result lists of two paths
return climb(steps + "1 ", remainingSteps -1)
+ climb(steps + "2 ", remainingSteps -2 );
}
}
答案 1 :(得分:0)
如果没有剩下的步骤,那么我们只想打印我们的路径。如果只剩下一步,那么我们不能采取两个步骤,所以我们采取一步并在路径中添加一个步骤。否则,我们采取一步,在我们的路径中添加一个。一旦完成并且我们回到了原来的位置,我们就会通过两个步骤做同样的事情。
void climb(int steps, String path) {
if (steps == 0) {
System.out.println(path);
} else if (steps == 1) {
climb(steps-1, path + "1 ");
} else {
climb(steps-1, path + "1 ");
climb(steps-2, path + "2 ");
}
}
答案 2 :(得分:0)
非常简单
public static void main(String[] args) {
printPath(4,"");
}
private static void printPath(int n,String path) {
if (n == 0) {
System.out.println(path.substring(1));
}
if (n-1 >=0) {
printPath(n-1,path + ",1");
}
if (n-2 >=0) {
printPath(n-2,path + ",2");
}
}