

- Главная
- Каталог
- Интернет технологии
- Python | LeetCode
Python | LeetCode
Разбираем задачи с LeetCode, с решением на языке программирования Python
Статистика канала
Полная статистикаchevron_right
Input: candidates = [2,3,5], target = 8
Output: [[2,2,2,2],[2,3,3],[3,5]]{}
class Solution:
def combinationSum(self, candidates, target):
results = []
def backtrack(remain, comb, start):
if remain == 0:
results.append(list(comb))
return
elif remain < 0:
return
for i in range(start, len(candidates)):
comb.append(candidates[i])
backtrack(remain - candidates[i], comb, i)
comb.pop()
backtrack(target, [], 0)
return results{}
Ставь 👍 и забирай 📚 Базу знанийs, удалите повторяющиеся буквы так, чтобы каждая буква появилась один раз и только один раз. Вы должны сделать так, чтобы результат был наименьшим в лексикографическом порядке среди всех возможных результатов.
Пример:
Input: s = "bcabc"
Output: "abc"{}
class Solution:
def removeDuplicateLetters(self, s) -> str:
stack = []
seen = set()
last_occurrence = {c: i for i, c in enumerate(s)}
for i, c in enumerate(s):
if c not in seen:
while stack and c < stack[-1] and i < last_occurrence[stack[-1]]:
seen.discard(stack.pop())
seen.add(c)
stack.append(c)
return ''.join(stack){}
Ставь 👍 и забирай 📚 Базу знаний
Input: words = ["cat","bt","hat","tree"], chars = "atach"
Output: 6
Explanation: The strings that can be formed are "cat" and "hat" so the answer is 3 + 3 = 6.{}
class Solution:
def countCharacters(self, words: List[str], chars: str) -> int:
counts = collections.Counter(chars)
ans = 0
for word in words:
wordCount = collections.Counter(word)
good = True
for c, freq in wordCount.items():
if counts[c] < freq:
good = False
break
if good:
ans += len(word)
return ans{}
Ставь 👍 и забирай 📚 Базу знаний
Input: tree = [7,4,3,null,null,6,19], target = 3
Output: 3
Explanation: In all examples the original and cloned trees are shown. The target node is a green node from the original tree. The answer is the yellow node from the cloned tree.{}
class Solution:
def getTargetCopy(self, original, cloned, target):
queue_o = [original]
queue_c = [cloned]
while queue_o:
node_o = queue_o.pop(0)
node_c = queue_c.pop(0)
if node_o is target:
return node_c
if node_o.left:
queue_o.append(node_o.left)
queue_c.append(node_c.left)
if node_o.right:
queue_o.append(node_o.right)
queue_c.append(node_c.right)
return None{}
Ставь 👍 и забирай 📚 Базу знаний
Input: tomatoSlices = 16, cheeseSlices = 7
Output: [1,6]{}
def numOfBurgers(tomatoSlices, cheeseSlices):
if tomatoSlices % 2 != 0 or tomatoSlices < 2 * cheeseSlices or tomatoSlices > 4 * cheeseSlices:
return []
total_jumbo = (tomatoSlices - 2 * cheeseSlices) // 2
total_small = cheeseSlices - total_jumbo
return [total_jumbo, total_small]{}
Ставь 👍 и забирай 📚 Базу знаний
Input: s1 = "great", s2 = "rgeat"
Output: true
Explanation: One possible scenario applied on s1 is:
"great" --> "gr/eat" // divide at random index.
"gr/eat" --> "gr/eat" // random decision is not to swap the two substrings and keep them in order.
"gr/eat" --> "g/r / e/at" // apply the same algorithm recursively on both substrings. divide at random index each of them.
"g/r / e/at" --> "r/g / e/at" // random decision was to swap the first substring and to keep the second substring in the same order.
"r/g / e/at" --> "r/g / e/ a/t" // again apply the algorithm recursively, divide "at" to "a/t".
"r/g / e/ a/t" --> "r/g / e/ a/t" // random decision is to keep both substrings in the same order.
The algorithm stops now, and the result string is "rgeat" which is s2.
As one possible scenario led s1 to be scrambled to s2, we return true.{}
class Solution:
def isScramble(self, s1: str, s2: str) -> bool:
n = len(s1)
dp = [
[[False for j in range(n)] for i in range(n)] for l in range(n + 1)
]
for i in range(n):
for j in range(n):
dp[1][i][j] = s1[i] == s2[j]
for length in range(2, n + 1):
for i in range(n + 1 - length):
for j in range(n + 1 - length):
for new_length in range(1, length):
dp1 = dp[new_length][i]
dp2 = dp[length - new_length][i + new_length]
dp[length][i][j] |= dp1[j] and dp2[j + new_length]
dp[length][i][j] |= (
dp1[j + length - new_length] and dp2[j]
)
return dp[n][0][0]{}
Ставь 👍 и забирай 📚 Базу знаний
Input: cards = [4,1,8,7]
Output: true
Explanation: (8-4) * (7-1) = 24{}
class Solution:
def generatePossibleResults(self, a, b):
res = [a + b, a - b, b - a, a * b]
if a != 0:
res.append(b / a)
if b != 0:
res.append(a / b)
return res
def checkIfResultReached(self, list):
if len(list) == 1:
return abs(list[0] - 24) <= 0.1
for i in range(len(list)):
for j in range(i + 1, len(list)):
new_list = [list[k] for k in range(len(list)) if k != i and k != j]
for res in self.generatePossibleResults(list[i], list[j]):
new_list.append(res)
if self.checkIfResultReached(new_list):
return True
new_list.pop()
return False
def judgePoint24(self, cards):
return self.checkIfResultReached(list(map(float, cards))){}
Ставь 👍 и забирай 📚 Базу знанийОтзывы канала
Каталог Телеграм-каналов для нативных размещений
Python | LeetCode — это Telegam канал в категории «Интернет технологии», который предлагает эффективные форматы для размещения рекламных постов в Телеграмме. Количество подписчиков канала в 10.0K и качественный контент помогают брендам привлекать внимание аудитории и увеличивать охват. Рейтинг канала составляет 5.6, количество отзывов – 0, со средней оценкой 0.0.
Вы можете запустить рекламную кампанию через сервис Telega.in, выбрав удобный формат размещения. Платформа обеспечивает прозрачные условия сотрудничества и предоставляет детальную аналитику. Стоимость размещения составляет 2377.62 ₽, а за 6 выполненных заявок канал зарекомендовал себя как надежный партнер для рекламы в TG. Размещайте интеграции уже сегодня и привлекайте новых клиентов вместе с Telega.in!
Вы снова сможете добавить каналы в корзину из каталога
Комментарий