Leetcode - Expression Add Operators (Python)

preview_player
Показать описание
September 2021 Leetcode Challenge
Leetcode - Expression Add Operators #282
Difficulty: Hard
Рекомендации по теме
Комментарии
Автор

Hi Tim,
Loved this, thanks. Been following your videos from a long time now. Just a suggestion would like you to go step by step like you've gone in this video for slow paced learners like me.

shashankmadan
Автор

You are amazing!!! Thank you so so much for sharing and explaining!

Tyokok
Автор

this is difficult man the dfs function is tricky.

pritam
Автор

Using the eval function still works, but it just barely passes. I don't think I could have figured out the trick with keeping the prev and result so far states >.<

class Solution:
def addOperators(self, num: str, target: int) -> List[str]:
'''
using eval function
'''
ans = []
def rec(i, curr, result, ApplyOpt, size):
if i == len(num):
result = result + str(curr)
if eval(result) == target:
ans.append(result)
return

if size == 0 or curr > 0:
rec(i + 1, curr * 10 + int(num[i]), result, True, 1)
if ApplyOpt:
rec(i, 0, result + str(curr) + '+', False, 0) # add PLUS
rec(i, 0, result + str(curr) + '-', False, 0) # add MINUS
rec(i, 0, result + str(curr) + '*', False, 0) # add PRODUCT

rec(0, 0, "", False, 0)
return ans

janmichaelaustria
welcome to shbcf.ru