4根柱子的漢諾塔,漢諾塔題目的變形,有4根柱子,可以把頂部的k個盤子移到最後的柱子上,然後按照漢諾塔,問最後走的最小步數。
思路:
一開始看了看以前的漢諾塔問題,遞歸。而這個漢諾塔問題主要是找規律了,看了好久也沒找到,最後看了題解,感覺遇到這種題目,自己很難做出來,還需要加強!
代碼:
import java.math.BigInteger;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
BigInteger[] f=new BigInteger[10005];
BigInteger two =new BigInteger("2");
BigInteger temp= BigInteger.ONE;
f[0] = BigInteger.ZERO;
int cnt=0,k=1;
for(int i=1;i<=10001;i++){
f[i]=f[i-1].add(temp);
cnt++;
if(cnt==k) {
cnt=0;
k++;
temp=temp.multiply(two);
}
}
while(in.hasNext()) {
int n=in.nextInt();
System.out.println(f[n]);
}
in.close();
}
}
地址:點擊打開鏈接