我正在尝试解决此问题: problem
通过动态编程,我能够解决问题,到目前为止这是代码:
import java.util.Scanner;
public class Dy
{
static long[] storage = new long[20];
public static void main(String[] args)
{
Scanner sx = new Scanner(System.in);
storage[0] = sx.nextInt();
storage[1] = sx.nextInt();
int x = sx.nextInt();
System.out.println(beast(x-1));
}
public static long beast(int n)
{
if(n==0)
return storage[n];
if(n==1)
return storage[n];
if(storage[n]!=0)
return storage[n];
storage[n] = (beast(n-1)*beast(n-1)) + beast(n-2);
return storage[n];
}
}
但真正的麻烦在这里,如果n大约是20,那么即使long
数据类型也不会保留该值,因此选择显然是BigInteger
,但作为一个学习者,我想知道如何在Java中使用BigInteger
和数组?任何帮助将不胜感激,谢谢!
答案 0 :(得分:1)
你可以使用Map<Integer, BigInteger>
之类的东西,
static Map<Integer, BigInteger> storage = new HashMap<>();
public static void main(String[] args) {
Scanner sx = new Scanner(System.in);
// Add 0 and 1.
storage.put(0, BigInteger.valueOf(sx.nextInt()));
storage.put(1, BigInteger.valueOf(sx.nextInt()));
int x = sx.nextInt();
System.out.println(beast(x - 1));
}
public static BigInteger beast(int n) {
if (!storage.containsKey(n)) {
BigInteger t = beast(n - 1);
storage.put(n, t.multiply(t).add(beast(n - 2)));
}
return storage.get(n);
}