본문 바로가기
IT/LeetCode

[LeetCode] 96. Unique Binary Search Trees

by 강천구 2023. 1. 15.

Given an integer n, return the number of structurally unique BST's (binary search trees) which has exactly n nodes of unique values from 1 to n.

 

Example 1:

Input: n = 3
Output: 5

Example 2:

Input: n = 1
Output: 1

 

Constraints:

  • 1 <= n <= 19
반응형

숫자 n이 주어졌을 때 1~n까지 숫자를 이용하여 유니크한 BST 구조를 몇개가 존재하는지 묻는 문제이다.

이 문제는 카탈란 수(Catalan number) 수열로 해결할 수 있다.

Catalan number
카탈란 수 점화식

카탈란 수 점화식을 재귀함수로 구현하게 되면 아래 코드와 같다.

class Solution:
    def numTrees(self, n: int) -> int:
        # catalan_num
        def calcul(num: int) -> int:
            if num == 0:
                return 1
            else:
                return calcul(num - 1) * 2 * (2 * num + 1) // (num + 2)

        return calcul(n - 1)

 

 

문제 출처 : https://leetcode.com/problems/unique-binary-search-trees/

 

Unique Binary Search Trees - LeetCode

Unique Binary Search Trees - Given an integer n, return the number of structurally unique BST's (binary search trees) which has exactly n nodes of unique values from 1 to n.   Example 1: [https://assets.leetcode.com/uploads/2021/01/18/uniquebstn3.jpg] Inp

leetcode.com

Github : https://github.com/kkkkang1009/leetcode/blob/master/leetcode_96.py

 

GitHub - kkkkang1009/leetcode: leetcode

leetcode. Contribute to kkkkang1009/leetcode development by creating an account on GitHub.

github.com

 

반응형

'IT > LeetCode' 카테고리의 다른 글

[LeetCode] 91. Decode Ways  (0) 2022.12.08
[LeetCode] 88. Merge Sorted Array  (0) 2022.11.15
[LeetCode] 83. Remove Duplicates from Sorted List  (0) 2022.10.27
[LeetCode] 70. Climbing Stairs  (0) 2022.08.19
[LeetCode] 69. Sqrt(x)  (0) 2022.08.19

댓글