题意:求一个长度为 n 的由0和1组成的序列中,满足没有两个 1 相邻的序列的数目。如 n = 3 时,000、001、010、100、101 一共 5 个序列满足条件。
分析:
n = 0 时,0个;n = 1 时,2个;n = 2 时,3个;
n = 3 时,5个;n = 4 时,8个…… n = n 时,f(f-1) + f(n-2) 个。
分析得:这是斐波那契数列的应用。
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
int scenario;
int[] f = new int[50];
FibonacciPlus(f);
while (in.hasNext()) {
scenario = in.nextInt();
for (int i = 1; i <= scenario; i++) {
out.println("Scenario #" + i + ":");
out.println(f[in.nextInt()]);
if (i != scenario)
out.println();
}
}
out.flush();
}
//*// 方法一:预处理,斐波那契数组打表。
public static void FibonacciPlus(int[] arr) {
arr[0] = 0;
arr[1] = 2;
arr[2] = 3;
for (int i = 3; i < 48; i++) {
arr[i] = arr[i - 1] + arr[i - 2];
}
}
//*/
/*// 方法二:计算
public static BigInteger Fibonacci(int n) {
if (n == 0) {
return BigInteger.valueOf(0);
}
if (n == 1) {
return BigInteger.valueOf(2);
}
if (n == 2) {
return BigInteger.valueOf(3);
}
BigInteger one = BigInteger.valueOf(3);
BigInteger two = BigInteger.valueOf(2);
BigInteger sum = BigInteger.valueOf(0);
for (int i = 3; i <= n; i++) {
sum = one.add(two);
two = one;
one = sum;
}
return sum;
}//*/
}