Problem Solving/LeetCode

Today's Challenge

fabichoi 2022. 8. 9. 23:45

https://leetcode.com/problems/binary-trees-with-factors/

 

Binary Trees With Factors - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

오늘은 솔루션만 봄.

class Solution:
    def numFactoredBinaryTrees(self, arr: List[int]) -> int:
        mod = 10 ** 9 + 7
        n = len(arr)
        arr.sort()
        dp = [1] * n
        index = {x: i for i, x in enumerate(arr)}
        for i, x in enumerate(arr):
            for j in range(i):
                if x % arr[j] == 0:
                    right = x / arr[j]
                    if right in index:
                        dp[i] += dp[j] * dp[index[right]]
                        dp[i] %= mod

        return sum(dp) % mod
반응형