๐ข์ด์ ์ ํ์ด์ฌ ๋ฒ์ ์ผ๋ก ์ ๋ฆฌํ ๊ฒ์ด ์์ผ๋ฏ๋ก, ์์ธํ ๋ด์ฉ์ ์ฝ๋ฉํ ์คํธ-์ฌ์ธ์[ํ์ด์ฌ ๋ฒ์ ]์ ์ฐธ๊ณ ํ์๊ธฐ ๋ฐ๋๋๋ค.
๐คฉ๊ธฐ์กด์ ํผ๋ณด๋์น top-down, bottom-up์ ์๋ฐ ๋ฒ์ ์ผ๋ก ๊ตฌํํด๋ณด์๋ค๐
public class Fibonacci {
public int fib(int n) {
HashMap<Integer, Integer> memo = new HashMap<>();
return dp(n, memo);
}
private static int dp(int n, HashMap<Integer, Integer> memo) {
// base condition
if (n <= 1) {
return n;
}
// n์ด ๋ฉ๋ชจ๋ฆฌ์ ์์ผ๋ฉด ์ฌ๊ท ํจ์๋ฅผ ํธ์ถ
if (!memo.containsKey(n)) {
memo.put(n, dp(n - 1, memo) + dp(n - 2, memo));
}
// n์ด ๋ฉ๋ชจ๋ฆฌ์ ์์ผ๋ฉด ๋ฉ๋ชจ๋ฆฌ์ ์๋ value๋ฅผ ๋ฆฌํด
return memo.get(n);
}
static์ผ๋ก ์ ์ธํ์๋ค.๐์ฐธ๊ณ ๋ก, dp๋ฅผ int[] dp = new int[n + 1];๊ณผ ๊ฐ์ด ๋ฐฐ์ด๋ก ์ ์ธํ ์๋ ์์ง๋ง, value๊ฐ ์์๊ฐ์ผ๋ก ์ฃผ์ด์ง ์๋ ์์ผ๋ฏ๋ก ํด์๋งต์ผ๋ก ์ด๊ธฐํํ๋ ๊ฒ์ด ๋ ํจ์จ์ ์ด๋ผ๊ณ ํ๋ค.
public class Fibonacci {
public int fib(int n) {
int[] table = new int[n + 1]; // ๋ฐฐ์ด์ 0๋ถํฐ ์์ํ๋ฏ๋ก 1์ ๋ํด์ค์ผํจ
return bottomUp(n, table);
}
private static int bottomUp(int n, int[] table) {
// base condition
table[0] = 0;
table[1] = 1;
for (int i = 2; i < n + 1; i++) {
table[i] = table[i - 1] + table[i - 2];
}
return table[n];
}
โ ๏ธ๊ฐ๋ ์ ์๋ฌด๋ฆฌ ์ถฉ์คํ ์ดํดํ๋ค๊ณ ํด๋, ์์ ํ์๋ถํฐ DP ๋ฌธ์ ๋ผ๊ณ ํ์ ํ๊ธฐ๊น์ง ์ค๋๊ฑธ๋ฆฌ๊ธฐ ๋๋ฌธ์ ๋ฌธ์ ๋ฅผ ๋ง์ด ํ์ด๋ณด๋ ์ ๋ฐ์ ์์!
๐3. Top-down -> Bottom-up์ผ๋ก ์ฝ๋ ์ ํ์ ๊ณ ๋ ค
๐์
๋ ฅ ํฌ๊ธฐ, ์ฑ๋ฅ, ๊ณต๊ฐ ์ต์ ํ๊ฐ ํ์ํ ๋๋ง ๊ณ ๋ ค
๐๋ชฐ๋ก Bottom-up์ table๋ก ์ฌ์ฉ๋๋ base condition์ ํด์๋งต์ผ๋ก ๊ตฌํํด๋ ์๊ด์๋ค.
๋ค๋ง, ๊ฐ์ธ์ ์ธ ๊ฒฌํด๋ก๋ ์ฝํ
์ฉ์ผ๋ก DP๋ฅผ ํ ๋ Top-down์ผ๋ก ํ๋ฆฌ๋ ๋ฌธ์ ๋ฅผ ๊ตณ์ด ์ต์ ํ๋ฅผ ์ํด์ Bottom-up์ผ๋ก ์ฝ๋๋ฅผ migrate๋ฅผ ํ ํ์๋ ์๋ค๊ณ ๋ณธ๋ค.(์ฌ์ง์ด ํ๋์จ์ด ์ฑ๋ฅ์ด ์ข๊ธฐ ๋๋ฌธ์ ๊ณต๊ฐ ๋ณต์ก๋๋ฅผ ๊ณ ๋ คํ ํ์๋ ์๋ค.)
๐๊ฐ์ฅ ์ค์ํ ์ ์, ๋๋ถ๋ถ์ ์ ํ์(reccurence relation)์ ์ฌ๊ท๋ฅผ ํ์ฉํ Top-down์ผ๋ก ๊ตฌํ๋๊ธฐ ๋๋ฌธ์ ์ง๊ด์ ์ธ ํ์ด๋ก ๋น ๋ฅด๊ฒ ๋ฌธ์ ๋ฅผ ํ๊ณ ์ถ๋ค๋ฉด Top-down์ ๊ณ ์ํด๋ ๋ฌธ์ ์๋ค!