暴力的な再帰
public class Test {
public static void main(String[] args) {
for (int i = 0; i < 20; i++) {
System.out.print(test(i) + ",");
}
}
static int test(int a) {
if (a == 0 || a == 1) return 1;
return test(a - 1) + test(a - 2);
}
}
メモ付きの再帰的ソリューション
public class Test {
public static void main(String[] args) {
int[] mono = new int[20];
for (int i = 0; i < 20; i++) {
System.out.print(test(mono, i) + "\t");
}
}
static int test(int[] mono, int a) {
if (a == 0 || a == 1) return 1;
if (mono[a] != 0) return mono[a];
return test(mono, a - 1) + test(mono, a - 2);
}
}
dp配列の反復解
import java.util.Arrays;
public class Test {
public static void main(String[] args) {
int[] dp = new int[20];
dp[0] = dp[1] = 1;
for (int i = 2; i < 20; i++) {
dp[i] = dp[i - 1] + dp[i - 2];
}
System.out.println(Arrays.toString(dp));
}
}
dp配列の反復解法に基づく状態圧縮
public class Test {
public static void main(String[] args) {
for (int i = 0; i < 20; i++) {
System.out.print(test(i) + " ");
}
}
static int test(int a) {
if (a == 0 || a == 1) return 1;
int pre = 1;
int curr = 1;
int sum;
for (int i = 1; i < a; i++) {
sum = pre + curr;
pre = curr;
curr = sum;
}
return curr;
}
}
これは、DPテーブルのサイズをnから2に減らすことと同じです。