Press "Enter" to skip to content

Posts published in “Uncategorized”

花花酱 LeetCode 921. Minimum Add to Make Parentheses Valid

Given a stringĀ SĀ ofĀ '('Ā andĀ ')'Ā parentheses, we add the minimum number of parentheses (Ā '('Ā orĀ ')', and in any positions ) so that the resulting parentheses string is valid.

Formally, a parentheses string is valid if and only if:

  • It is the empty string, or
  • It can be written asĀ ABĀ (AĀ concatenated withĀ B), whereĀ AĀ andĀ BĀ are valid strings, or
  • It can be written asĀ (A), whereĀ AĀ is a valid string.

Given a parentheses string, return the minimum number of parentheses we must add to make the resulting string valid.

 

Example 1:

Input: "())"
Output: 1

Example 2:

Input: "((("
Output: 3

Example 3:

Input: "()"
Output: 0

Example 4:

Input: "()))(("
Output: 4

Note:

  1. S.length <= 1000
  2. SĀ only consists ofĀ '('Ā andĀ ')'Ā characters.

Solution: Counting

Time complexity: O(n)

Space complexity: O(1)

C++

花花酱 LeetCode 633. Sum of Square Numbers

Problem

Given a non-negative integerĀ c, your task is to decide whether there’re two integersĀ aĀ andĀ bĀ such that a2Ā + b2Ā = c.

Example 1:

Input: 5
Output: True
Explanation: 1 * 1 + 2 * 2 = 5

Example 2:

Input: 3
Output: False

Solution: Math

Time complexity: O(sqrt(c))

Space complexity: O(1)

 

花花酱 LeetCode 95. Unique Binary Search Trees II

Problem

https://leetcode.com/problems/unique-binary-search-trees-ii/description/

Given an integerĀ n, generate all structurally uniqueĀ BST’sĀ (binary search trees) that store values 1…n.

For example,
GivenĀ nĀ = 3, your program should return all 5 unique BST’s shown below.

Ā 

Idea: Recursion

for i in 1..n: pick i as root,
left subtrees can be generated in the same way for n_l = 1 … i – 1,
right subtrees can be generated in the same way for n_r = i + 1, …, n
def gen(s, e):
return [tree(i, l, r) for l in gen(s, i – 1) for r in gen(i + 1, e) for i in range(s, e+1)

# of trees:

n = 0: 1
n = 1: 1
n = 2: 2
n = 3: 5
n = 4: 14
n = 5: 42
n = 6: 132

Trees(n) = Trees(0)*Trees(n-1) + Trees(1)*Trees(n-2) + … + Tress(n-1)*Trees(0)

Time complexity: O(3^n)

Space complexity: O(3^n)

C++

Java

Python 3

Solution 2: DP

Java

Related Problems