题解 | #汉诺塔问题#
汉诺塔问题
https://www.nowcoder.com/practice/7d6cab7d435048c4b05251bf44e9f185
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param n int整型 * @return string字符串ArrayList */ //自定义递归函数完成问题 public ArrayList<String> getSolution (int n) { // write code here String s1 = "left"; String s2 = "mid"; String s3 = "right"; ArrayList<String> strs = new ArrayList<>(); function(n, s1, s2, s3, strs); return strs; } public void function(int n, String s1, String s2, String s3, ArrayList<String> strs){ if (n == 1) { strs.add("move from " + s1 + " to " + s3); } else { function(n - 1, s1, s3, s2, strs); strs.add("move from " + s1 + " to " + s3); function(n - 1, s2, s1, s3, strs); } } }