파비의 매일매일 공부기록

2023.05.11 Today's Challenge 본문

Problem Solving/LeetCode

2023.05.11 Today's Challenge

fabichoi 2023. 5. 11. 23:45

https://leetcode.com/problems/uncrossed-lines/

 

Uncrossed Lines - LeetCode

Can you solve this real interview question? Uncrossed Lines - You are given two integer arrays nums1 and nums2. We write the integers of nums1 and nums2 (in the order they are given) on two separate horizontal lines. We may draw connecting lines: a straigh

leetcode.com

단순 한 방향으로 진행하는게 아니라, 양방향으로 봐야되는 케이스가 존재함.
그래서 DP로 풀어야 됨.

class Solution:
    def maxUncrossedLines(self, nums1: List[int], nums2: List[int]) -> int:
        n1, n2 = len(nums1), len(nums2)
        memo = {}
        def solve(i, j):
            if i <= 0 or j <= 0:
                return 0            
            if (i, j) in memo:
                return memo[(i, j)]            
            if nums1[i-1] == nums2[j-1]:
                memo[(i,j)] = 1 + solve(i-1, j-1)
            else:
                memo[(i,j)] = max(solve(i-1, j), solve(i, j-1))            
            return memo[(i, j)]
        return solve(n1, n2)
반응형

'Problem Solving > LeetCode' 카테고리의 다른 글

2023.05.13 Today's Challenge  (1) 2023.05.13
2023.05.12 Today's Challenge  (0) 2023.05.12
2023.05.10 Today's Challenge  (0) 2023.05.10
2023.05.09 Today's Challenge  (0) 2023.05.09
2023.05.08 Today's Challenge  (0) 2023.05.08
Comments