|
| 1 | +/** |
| 2 | + * [Problem]: [1143] Longest Common Subsequence |
| 3 | + * (https://leetcode.com/problems/longest-common-subsequence/description/) |
| 4 | + */ |
| 5 | +function longestCommonSubsequence(text1: string, text2: string): number { |
| 6 | + //시간복잡도 O(2^n) |
| 7 | + //공간복잡도 O(n) |
| 8 | + // Time Limit Exceeded |
| 9 | + function dfsFunc(text1: string, text2: string): number { |
| 10 | + function dfs(i: number, j: number): number { |
| 11 | + if (i === text1.length || j === text2.length) return 0; |
| 12 | + |
| 13 | + if (text1[i] === text2[j]) { |
| 14 | + return 1 + dfs(i + 1, j + 1); |
| 15 | + } else { |
| 16 | + return Math.max(dfs(i, j + 1), dfs(i + 1, j)); |
| 17 | + } |
| 18 | + } |
| 19 | + |
| 20 | + return dfs(0, 0); |
| 21 | + } |
| 22 | + |
| 23 | + //시간복잡도 O(n) |
| 24 | + //공간복잡도 O(n) |
| 25 | + function memoizationFunc(text1: string, text2: string): number { |
| 26 | + const memo = new Map<string, number>(); |
| 27 | + |
| 28 | + function dfs(i: number, j: number) { |
| 29 | + if (i === text1.length || j === text2.length) return 0; |
| 30 | + |
| 31 | + const key = `${i}, ${j}`; |
| 32 | + if (memo.has(key)) return memo.get(key)!; |
| 33 | + |
| 34 | + let result = 0; |
| 35 | + if (text1[i] === text2[j]) { |
| 36 | + result = 1 + dfs(i + 1, j + 1); |
| 37 | + } else { |
| 38 | + result = Math.max(dfs(i, j + 1), dfs(i + 1, j)); |
| 39 | + } |
| 40 | + |
| 41 | + memo.set(key, result); |
| 42 | + return result; |
| 43 | + } |
| 44 | + |
| 45 | + return dfs(0, 0); |
| 46 | + } |
| 47 | + |
| 48 | + //시간복잡도 O(n) |
| 49 | + //공간복잡도 O(n) |
| 50 | + function dpFunc(tex1: string, text2: string): number { |
| 51 | + const length1 = text1.length; |
| 52 | + const length2 = text2.length; |
| 53 | + const dp: number[][] = Array.from({ length: length1 + 1 }, () => |
| 54 | + Array(length2 + 1).fill(0) |
| 55 | + ); |
| 56 | + |
| 57 | + for (let i = 1; i <= length1; i++) { |
| 58 | + for (let j = 1; j <= length2; j++) { |
| 59 | + if (text1[i - 1] === text2[j - 1]) { |
| 60 | + dp[i][j] = 1 + dp[i - 1][j - 1]; |
| 61 | + } else { |
| 62 | + dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]); |
| 63 | + } |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + return dp[length1][length2]; |
| 68 | + } |
| 69 | +} |
0 commit comments