Skip to content

Commit

Permalink
-
Browse files Browse the repository at this point in the history
  • Loading branch information
SamirPaulb committed Feb 4, 2022
1 parent 66fe0d4 commit 73a6bde
Show file tree
Hide file tree
Showing 4 changed files with 69 additions and 4 deletions.

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# https://leetcode.com/problems/unique-binary-search-trees/
# https://youtu.be/H1qjjkm3P3c
class Solution:
def numTrees(self, n: int) -> int:
'''
# Recursive Solution
def solve(n):
if n <= 1: return 1
if n == 2: return 2
if n == 3: return 5
ans = 0
for i in range(n):
ans += solve(i) * solve(n-i-1)
return ans
return solve(n)
'''
# Dynamic Programming
dp = [0] * (n+1)
dp[0] = 1

for i in range(1, n+1):
for j in range(i):
dp[i] += dp[j] * dp[i-j-1]

return dp[-1]

# Time: O(n*n)
# Space: O(n)
2 changes: 0 additions & 2 deletions 12_Backtracking/15. .py

This file was deleted.

40 changes: 40 additions & 0 deletions 12_Backtracking/15. Jump Game III.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
# https://leetcode.com/problems/jump-game-iii/

# -------------------------- DFS Approach -------------------------------
class Solution:
def canReach(self, arr, start):
seen = set()

def dfs(n):
if n in seen: return False
if not 0 <= n < len(arr): return False
if arr[n] == 0: return True
seen.add(n)
return dfs(n - arr[n]) or dfs(n + arr[n])

return dfs(start)

# Time O(N); as traversing evry element only once
# Space: O(N)


# -------------------------- BFS Approach -------------------------------
class Solution:
def canReach(self, arr, start):
q = [start]
visited = [False]*len(arr)

while q:
tmp = q.pop()
if arr[tmp] == 0: return True
visited[tmp] = True
r, l = tmp + arr[tmp], tmp - arr[tmp]
if r < len(arr) and visited[r] == False:
q.append(r)
if l >= 0 and visited[l] == False:
q.append(l)

return False

# Time O(N); as traversing evry element only once
# Space: O(N)

0 comments on commit 73a6bde

Please sign in to comment.