Skip to content

Commit 96e2dfb

Browse files
committed
update 120
1 parent 3db8fb3 commit 96e2dfb

File tree

6 files changed

+156
-97
lines changed

6 files changed

+156
-97
lines changed

README.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,7 @@ python problem.py https://www.lintcode.com/problem/92 -l cpp
9494
## Dynamic Programming
9595
| Problem | Solution | Time | Space | Note | Ref |
9696
| ----- | ----- | ----- | ----- | ----- | ----- |
97+
| [Leetcode-120. Triangle](https://leetcode.com/problems/triangle/description/) | [c++](./leetcode/120.triangle.cpp), [python](./leetcode/120.triangle.py) | O\(N^2\) | O\(N\) | \- | - |
9798
| [Leetcode-1575. Count All Possible Routes](https://leetcode.com/problems/count-all-possible-routes/description/) | [c++](./leetcode/1575.count-all-possible-routes.cpp), [python](./leetcode/1575.count-all-possible-routes.py) | \- | \- | \- | - |
9899
| [Leetcode-375. Guess Number Higher Or Lower II](https://leetcode.com/problems/guess-number-higher-or-lower-ii/description/) | [c++](./leetcode/375.guess-number-higher-or-lower-ii.cpp), [python](./leetcode/375.guess-number-higher-or-lower-ii.py) | O\(N^3\) | O\(N^2\) | DP\(Index\) | - |
99100
| [Leetcode-322. Coin Change](https://leetcode.com/problems/coin-change/description/) | [c++](./leetcode/322.coin-change.cpp), [python](./leetcode/322.coin-change.py) | O\(K \* N\) | O\(N\) | Index | [Video](https://youtu.be/EjMjlFjLRiM) |
@@ -235,7 +236,6 @@ python problem.py https://www.lintcode.com/problem/92 -l cpp
235236
| [Leetcode-115. Distinct Subsequences](https://leetcode.com/problems/distinct-subsequences/description/) | [c++](./leetcode/115.distinct-subsequences.cpp), [python](./leetcode/115.distinct-subsequences.py) | \- | \- | \- | - |
236237
| [Leetcode-118. Pascals Triangle](https://leetcode.com/problems/pascals-triangle/description/) | [c++](./leetcode/118.pascals-triangle.cpp), [python](./leetcode/118.pascals-triangle.py) | \- | \- | \- | - |
237238
| [Leetcode-119. Pascals Triangle II](https://leetcode.com/problems/pascals-triangle-ii/description/) | [c++](./leetcode/119.pascals-triangle-ii.cpp), [python](./leetcode/119.pascals-triangle-ii.py) | \- | \- | \- | - |
238-
| [Leetcode-120. Triangle](https://leetcode.com/problems/triangle/description/) | [c++](./leetcode/120.triangle.cpp), [python](./leetcode/120.triangle.py) | \- | \- | \- | - |
239239
| [Leetcode-121. Best Time To Buy And Sell Stock](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description/) | [c++](./leetcode/121.best-time-to-buy-and-sell-stock.cpp), [python](./leetcode/121.best-time-to-buy-and-sell-stock.py) | \- | \- | \- | - |
240240
| [Leetcode-122. Best Time To Buy And Sell Stock II](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/description/) | [c++](./leetcode/122.best-time-to-buy-and-sell-stock-ii.cpp), [python](./leetcode/122.best-time-to-buy-and-sell-stock-ii.py) | \- | \- | \- | - |
241241
| [Leetcode-123. Best Time To Buy And Sell Stock III](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/description/) | [c++](./leetcode/123.best-time-to-buy-and-sell-stock-iii.cpp), [python](./leetcode/123.best-time-to-buy-and-sell-stock-iii.py) | \- | \- | \- | - |
@@ -294,7 +294,7 @@ python problem.py https://www.lintcode.com/problem/92 -l cpp
294294
| [Leetcode-253. Meeting Rooms II](https://leetcode.com/problems/meeting-rooms-ii/description/) | [c++](./leetcode/253.meeting-rooms-ii.cpp), [python](./leetcode/253.meeting-rooms-ii.py) | \- | \- | \- | - |
295295
| [Leetcode-256. Paint House](https://leetcode.com/problems/paint-house/description/) | [c++](./leetcode/256.paint-house.cpp), [python](./leetcode/256.paint-house.py) | \- | \- | \- | - |
296296
| [Leetcode-261. Graph Valid Tree](https://leetcode.com/problems/graph-valid-tree/description/) | [c++](./leetcode/261.graph-valid-tree.cpp), [python](./leetcode/261.graph-valid-tree.py) | \- | \- | \- | - |
297-
| [Leetcode-263. Ugly Number](https://leetcode.com/problems/ugly-number/description/) | [c++](./leetcode/263.ugly-number.cpp), [python](./leetcode/263.ugly-number.py) | \- | \- | \- | - |
297+
| [Leetcode-263. Ugly Number](https://leetcode.com/problems/ugly-number/description/) | [c++](./leetcode/263.ugly-number.cpp), [python](./leetcode/263.ugly-number.py) | O\(k\) | O\(1\) | \- | - |
298298
| [Leetcode-265. Paint House II](https://leetcode.com/problems/paint-house-ii/description/) | [c++](./leetcode/265.paint-house-ii.cpp), [python](./leetcode/265.paint-house-ii.py) | \- | \- | \- | - |
299299
| [Leetcode-269. Alien Dictionary](https://leetcode.com/problems/alien-dictionary/description/) | [python](./leetcode/269.alien-dictionary.py) | \- | \- | \- | - |
300300
| [Leetcode-270. Closest Binary Search Tree Value](https://leetcode.com/problems/closest-binary-search-tree-value/description/) | [c++](./leetcode/270.closest-binary-search-tree-value.cpp), [python](./leetcode/270.closest-binary-search-tree-value.py) | \- | \- | \- | - |
@@ -438,5 +438,5 @@ python problem.py https://www.lintcode.com/problem/92 -l cpp
438438
Total sovled: **320**<br/>
439439
PS: semicolon(;) after each note means related questions are checked<br/>
440440
<br/>
441-
Auto updated at: **2024-06-09 23:07:43**<br/>
441+
Auto updated at: **2024-06-25 11:34:45**<br/>
442442

leetcode/120.triangle.cpp

Lines changed: 45 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,52 @@
1-
//for each node f[parent] = min(f[left-child], f[right-child]) + val
1+
// Category: Array, Dynamic Programming
2+
// Time: O(N^2)
3+
// Space: O(N)
4+
// Ref: -
5+
// Note: -
6+
7+
// Given a triangle array, return the minimum path sum from top to bottom.
8+
// For each step, you may move to an adjacent number of the row below. More formally, if you are on index i on the current row, you may move to either index i or index i + 1 on the next row.
9+
//  
10+
// Example 1:
11+
//
12+
// Input: triangle = [[2],[3,4],[6,5,7],[4,1,8,3]]
13+
// Output: 11
14+
// Explanation: The triangle looks like:
15+
// 2
16+
// 3 4
17+
// 6 5 7
18+
// 4 1 8 3
19+
// The minimum path sum from top to bottom is 2 + 3 + 5 + 1 = 11 (underlined above).
20+
//
21+
// Example 2:
22+
//
23+
// Input: triangle = [[-10]]
24+
// Output: -10
25+
//
26+
//  
27+
// Constraints:
28+
//
29+
// 1 <= triangle.length <= 200
30+
// triangle[0].length == 1
31+
// triangle[i].length == triangle[i - 1].length + 1
32+
// -104 <= triangle[i][j] <= 104
33+
//
34+
//  
35+
// Follow up: Could you do this using only O(n) extra space, where n is the total number of rows in the triangle?
36+
237
class Solution {
338
public:
439
int minimumTotal(vector<vector<int>>& triangle) {
40+
int n = triangle.size();
41+
vector<int> dp = triangle.back();
542

6-
if (triangle.size() == 0 || triangle[0].size() == 0)
7-
{
8-
return 0;
9-
}
10-
11-
int size = (int)(triangle.size());
12-
vector<int> table(size, 0);
13-
14-
// init
15-
for (auto j = 0; j < size; ++j)
16-
{
17-
table[j] = triangle[size - 1][j];
18-
}
19-
20-
for(auto i = size - 2; i >= 0; --i)
21-
{
22-
for(auto j = 0; j <= i; ++j)
23-
{
24-
table[j] = min(table[j], table[j + 1]) + triangle[i][j];
43+
for (int i = n - 2; i >= 0; i--) {
44+
for (int j = 0; j < triangle[i].size(); j++) {
45+
dp[j] = triangle[i][j] + min(dp[j], dp[j + 1]);
2546
}
2647
}
27-
28-
return table[0];
48+
49+
return dp[0];
50+
2951
}
30-
};
52+
};

leetcode/120.triangle.py

Lines changed: 46 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,30 +1,50 @@
1-
# x(row), y(column)
2-
# (0, 0)
3-
# (1, 0), (1, 1)
4-
# (2, 0), (2, 1), (2, 2)
5-
# (3, 0), (3, 1), (3, 2), (3, 3)
6-
7-
# DP bottom-up O(N^2)
8-
# f[i][j] = min(f[i + 1][j], f[i + 1][i + 1]) + triangle[i][j]
9-
class Solution(object):
10-
def minimumTotal(self, triangle):
11-
"""
12-
:type triangle: List[List[int]]
13-
:rtype: int
14-
"""
15-
if len(triangle) == 0 or len(triangle[0]) == 0:
16-
return 0
17-
18-
size = len(triangle)
19-
table = triangle[-1][:]
20-
21-
for i in range(size - 2, -1, -1):
1+
# Category: Array, Dynamic Programming
2+
# Time: O(N^2)
3+
# Space: O(N)
4+
# Ref: -
5+
# Note: -
6+
7+
# Given a triangle array, return the minimum path sum from top to bottom.
8+
# For each step, you may move to an adjacent number of the row below. More formally, if you are on index i on the current row, you may move to either index i or index i + 1 on the next row.
9+
#  
10+
# Example 1:
11+
#
12+
# Input: triangle = [[2],[3,4],[6,5,7],[4,1,8,3]]
13+
# Output: 11
14+
# Explanation: The triangle looks like:
15+
# 2
16+
# 3 4
17+
# 6 5 7
18+
# 4 1 8 3
19+
# The minimum path sum from top to bottom is 2 + 3 + 5 + 1 = 11 (underlined above).
20+
#
21+
# Example 2:
22+
#
23+
# Input: triangle = [[-10]]
24+
# Output: -10
25+
#
26+
#  
27+
# Constraints:
28+
#
29+
# 1 <= triangle.length <= 200
30+
# triangle[0].length == 1
31+
# triangle[i].length == triangle[i - 1].length + 1
32+
# -104 <= triangle[i][j] <= 104
33+
#
34+
#  
35+
# Follow up: Could you do this using only O(n) extra space, where n is the total number of rows in the triangle?
36+
37+
class Solution:
38+
def minimumTotal(self, triangle: List[List[int]]) -> int:
39+
n = len(triangle)
40+
dp = triangle[-1].copy()
41+
42+
for i in reversed(range(n - 1)):
2243
for j in range(len(triangle[i])):
23-
table[j] = min(table[j], table[j + 1]) + triangle[i][j]
24-
25-
return table[0]
26-
44+
dp[j] = triangle[i][j] + min(dp[j], dp[j + 1])
2745

46+
return dp[0]
47+
2848
# DP top-down O(N^2)
2949
class SolutionDP_top_down(object):
3050
def minimumTotal(self, triangle):
@@ -119,4 +139,4 @@ def dfs(self, triangle, tmp, x, y):
119139
tmp.append(triangle[x][y])
120140
self.dfs(triangle, tmp, x + 1, y)
121141
self.dfs(triangle, tmp, x + 1, y + 1)
122-
tmp.pop()
142+
tmp.pop()

leetcode/263.ugly-number.cpp

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
// Category: Math
2-
// Time: -
3-
// Space: -
2+
// Time: O(k)
3+
// Space: O(1)
44
// Ref: -
55
// Note: -
66

leetcode/263.ugly-number.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# Category: Math
2-
# Time: -
3-
# Space: -
2+
# Time: O(k)
3+
# Space: O(1)
44
# Ref: -
55
# Note: -
66

problem.py

Lines changed: 58 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -68,68 +68,85 @@ def write(self, file) -> None:
6868

6969
def parse_leetcode(url, lang, translate):
7070
session = requests.session()
71-
response = session.get(url)
72-
text = response.text
73-
74-
soup = BeautifulSoup(text, 'html.parser')
75-
76-
problem = soup.find('script', type='application/json')
77-
78-
json_text = problem.contents[0]
79-
80-
query = json.loads(json_text)['props']['pageProps']['dehydratedState']['queries']
8171

8272
problem = Problem('leetcode', lang)
83-
84-
for data in query:
85-
if 'questionTitle' in data['queryKey']:
86-
problem.number = data['state']['data']['question']['questionFrontendId']
87-
problem.title = data['state']['data']['question']['title']
88-
89-
elif 'questionContent' in data['queryKey']:
90-
if len(problem.content) == 0:
91-
content = BeautifulSoup(data['state']['data']['question']['content'], 'html.parser')
92-
problem.content = content.text
93-
94-
elif translate and 'questionTranslations' in data['queryKey']:
95-
content = BeautifulSoup(data['state']['data']['question']['translatedContent'], 'html.parser')
96-
problem.content = content.text
97-
98-
elif 'singleQuestionTopicTags' in data['queryKey']:
99-
problem.tags = [tag['name'] for tag in data['state']['data']['question']['topicTags']]
100-
101-
elif 'questionInterviewOptions' in data['queryKey']:
102-
companies = data['state']['data']['interviewed']['companies']
103-
problem.companies = [c['name'] for c in companies]
104-
else:
105-
# print(data['queryKey'][0])
106-
pass
107-
108-
109-
73+
problem.title = re.search(r"/problems/([\w-]+)/?", url).group(1)
74+
11075
graphql = urlparse(url)._replace(path="/graphql/").geturl()
111-
11276
headers = {
11377
'Referer': url,
11478
}
11579

116-
json_data = {
80+
question_title = {
81+
"query":"\n query questionTitle($titleSlug: String!) {\n question(titleSlug: $titleSlug) {\n questionId\n questionFrontendId\n title\n titleSlug\n isPaidOnly\n difficulty\n likes\n dislikes\n categoryTitle\n }\n}\n ",
82+
"variables":{
83+
"titleSlug": problem.question_name
84+
},
85+
"operationName":"questionTitle"
86+
}
87+
88+
response = session.post(graphql, headers=headers, json=question_title)
89+
data = response.json()
90+
problem.number = data["data"]["question"]["questionFrontendId"]
91+
problem.title = data['data']['question']['title']
92+
print(problem.number, problem.title)
93+
94+
question_content = {
95+
"query": "\n query questionContent($titleSlug: String!) {\n question(titleSlug: $titleSlug) {\n content\n mysqlSchemas\n dataSchemas\n }\n}\n ",
96+
"variables": {
97+
"titleSlug": problem.question_name
98+
},
99+
"operationName":"questionContent"
100+
}
101+
response = session.post(graphql, headers=headers, json=question_content)
102+
data = response.json()
103+
soup = BeautifulSoup(data["data"]["question"]["content"], 'html.parser')
104+
problem.content = soup.text
105+
106+
question_topic = {
107+
"query":"\n query singleQuestionTopicTags($titleSlug: String!) {\n question(titleSlug: $titleSlug) {\n topicTags {\n name\n slug\n }\n }\n}\n ",
108+
"variables": {
109+
"titleSlug": problem.question_name
110+
},
111+
"operationName":"singleQuestionTopicTags"
112+
}
113+
response = session.post(graphql, headers=headers, json=question_topic)
114+
data = response.json()
115+
problem.tags = [tag['name'] for tag in data['data']['question']['topicTags']]
116+
print(problem.tags)
117+
118+
question_editor = {
117119
'query': '\n query questionEditorData($titleSlug: String!) {\n question(titleSlug: $titleSlug) {\n questionId\n questionFrontendId\n codeSnippets {\n lang\n langSlug\n code\n }\n envInfo\n enableRunCode\n hasFrontendPreview\n frontendPreviews\n }\n}\n ',
118120
'variables': {
119-
'titleSlug': problem.question_name,
121+
'titleSlug': problem.question_name
120122
},
121123
'operationName': 'questionEditorData',
122124
}
123125

124-
response = session.post(graphql, headers=headers, json=json_data)
126+
response = session.post(graphql, headers=headers, json=question_editor)
125127
state = response.json()
126128
editorData = state['data']['question']['codeSnippets'] or []
127129
for code in editorData:
128130
if code['langSlug'].lower() == lang.lower():
129131
problem.editorData = code['code']
130132

133+
if translate:
134+
question_translattion = {
135+
"query":"\n query questionTranslations($titleSlug: String!) {\n question(titleSlug: $titleSlug) {\n translatedTitle\n translatedContent\n }\n}\n ",
136+
"variables": {
137+
"titleSlug": problem.question_name
138+
},
139+
"operationName":"questionTranslations"
140+
}
141+
142+
response = session.post(graphql, headers=headers, json=question_translattion)
143+
data = response.json()
144+
soup = BeautifulSoup(data["data"]["question"]["translatedContent"], 'html.parser')
145+
problem.content = soup.text
146+
131147
return problem
132148

149+
133150
def parse_lintcode(url, lang, translate):
134151

135152
numbers = re.findall(r'\d+', url)

0 commit comments

Comments
 (0)