代码的输出是1,1,2,2,3,3,4,4,而不是1,2,3,4。我尝试了很多不同的位置来使变量工作,但这是我得到的最接近的。我只是误解了递归的基本原理吗?
import java.util.Scanner;
public class TowerOfHanoi {
public static int a = 1;
public static void main(String[] args) {
TowerOfHanoi towerOfHanoi = new TowerOfHanoi();
System.out.println("Enter number of disks: ");
Scanner scan = new Scanner(System.in);
int disks = scan.nextInt();
towerOfHanoi.solve(disks, "1", "2", "3");
scan.close();
}
public void solve(int n, String start, String mid, String end){
if(n == 1){
System.out.println(a + " : "+ start + " to " + end);
a++;
} else {
solve(n-1, start, end, mid);
System.out.println(a + " : " + start + " to " + end);
solve(n-1, mid, start, end);
}
}
}
输出:
Enter number of disks:
3
1 : 1 to 3
2 : 1 to 2
2 : 3 to 2
3 : 1 to 3
3 : 2 to 1
4 : 2 to 3
4 : 1 to 3
答案 0 :(得分:1)
步骤顺序对我而言,但您忘记在a
的{{1}}子句中增加else
。
Solve应该看起来像这样:
solve(...)
答案 1 :(得分:0)
function pushToSitemap($initial_sitemap, $sitemap) {
foreach ($initial_sitemap as $title => $url) {
$sitemap[$title] = BASE_URL . $url;
}
return $sitemap;
}
$sitemap_full = pushToSitemap($sitemap_example, $sitemap_full);
应在每个a
之后递增,而不仅仅是第一个。