Skip to content

Commit 95617b6

Browse files
committed
leetcode #210
1 parent 0744014 commit 95617b6

File tree

2 files changed

+65
-8
lines changed

2 files changed

+65
-8
lines changed

course-schedule-ii.py

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
# https://leetcode.com/problems/course-schedule-ii/submissions/
2+
3+
class Solution(object):
4+
5+
def DepthFirstSearch(self, current, visited, currentSet, ans, prereq):
6+
7+
currentSet.add(current)
8+
9+
if current in prereq:
10+
for course in prereq[current]:
11+
12+
if course in visited:
13+
continue
14+
15+
if course in currentSet:
16+
return False
17+
18+
if not self.DepthFirstSearch(course, visited, currentSet, ans, prereq):
19+
return False
20+
21+
currentSet.remove(current)
22+
visited.add(current)
23+
24+
ans.append(current)
25+
26+
return ans
27+
28+
29+
def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
30+
31+
prereq = {}
32+
33+
for prerequisit in prerequisites:
34+
35+
if prerequisit[0] in prereq:
36+
prereq[prerequisit[0]].append(prerequisit[1])
37+
38+
else:
39+
prereq[prerequisit[0]] = [prerequisit[1]]
40+
41+
visited = set()
42+
ans = []
43+
44+
for course in range(numCourses):
45+
46+
if course in visited:
47+
continue
48+
49+
if not self.DepthFirstSearch(course, visited, set(), ans, prereq):
50+
return []
51+
52+
return ans

path-sum-iii.py

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -14,21 +14,26 @@ def DepthFirstSearch(self, root, sum):
1414

1515
if not root:
1616
return ans
17+
18+
else:
1719

18-
if root.val == sum:
19-
ans += 1
20+
if root.val == sum:
21+
ans = 1
22+
23+
ans += self.DepthFirstSearch(root.left, sum - root.val)
24+
ans += self.DepthFirstSearch(root.right, sum - root.val)
2025

21-
ans += self.DepthFirstSearch(root.left, sum - root.val)
22-
ans += self.DepthFirstSearch(root.right, sum - root.val)
23-
2426
return ans
2527

2628
def pathSum(self, root: 'TreeNode', sum: 'int') -> 'int':
27-
29+
ans = 0
30+
2831
if not root:
29-
return 0
32+
return ans
3033

3134
else:
32-
ans = self.DepthFirstSearch(root, sum) + self.pathSum(root.left, sum) + self.pathSum(root.right, sum)
35+
ans += self.DepthFirstSearch(root, sum)
36+
ans += self.pathSum(root.left, sum)
37+
ans += self.pathSum(root.right, sum)
3338

3439
return ans

0 commit comments

Comments
 (0)