Expression Add Operators
LeetCode 282 · கடினம் · தீர்வு, intuition & படிப்படியான வாக்த்ரூ
Track prev_operand to fix up multiplication precedence.
நான் Expression Add Operators (LeetCode 282) ஐ இப்படித் தீர்த்தேன் — Constraint Satisfaction பேட்டர்னின் ஒரு கடினம் பிராப்ளம். கீழே: intuition, படிப்படியான approach, என் accepted Python கோட், animated test cases மற்றும் line-by-line debugger.
கீழேயுள்ள விளக்கம் ஆங்கிலத்தில் உள்ளது.
Intuition
Try every way to cut the digit string into numbers and put +, − or * between them. Multiplication binds tighter, so remember the last operand: to apply *, undo it from the running value and add (last × current) instead.
Approach
- 1
dfs(index, value, prev, expr).
- 2
Try each next number num[index..i] (no leading zeros).
- 3
First number starts the expression.
- 4
+: value + cur; −: value − cur (prev = −cur); *: value − prev + prev·cur.
நான் எப்படித் தீர்த்தேன்
Backtracking with precedence fixPythonO(4ⁿ) time
class Solution:
def addOperators(self, num: str, target: int) -> List[str]:
res = []
def dfs(index,cur_val,prev_operand,expression):
if index==len(num):
if cur_val==target:
res.append(expression)
return
for i in range(index,len(num)):
if i!=index and num[index]=="0":
continue
cur_str = num[index:i+1]
cur_num = int(cur_str)
if index==0:
dfs(i+1,cur_num,cur_num,cur_str)
else:
#+
dfs(i+1,cur_val+cur_num,cur_num,expression+"+"+cur_str)
#-
dfs(i+1,cur_val-cur_num,-cur_num,expression+"-"+cur_str)
#*
#val-prevoperand+(prevoperand*cur_num)
dfs(i+1,cur_val-prev_operand+(prev_operand*cur_num),prev_operand * cur_num,expression+"*"+cur_str)
#(2,3*2,3-2+3*2, 1+2*3
dfs(0,0,0,"")
return res
Expression Add Operators — அடிக்கடி கேட்கப்படும் கேள்விகள்
Expression Add Operators பின்னாலுள்ள intuition என்ன?
Try every way to cut the digit string into numbers and put +, − or * between them. Multiplication binds tighter, so remember the last operand: to apply *, undo it from the running value and add (last × current) instead.
Expression Add Operators (LeetCode 282) ஐ எப்படித் தீர்ப்பது?
1. dfs(index, value, prev, expr). 2. Try each next number num[index..i] (no leading zeros). 3. First number starts the expression. 4. +: value + cur; −: value − cur (prev = −cur); *: value − prev + prev·cur.
Expression Add Operators இன் time மற்றும் space complexity என்ன?
Time: O(4ⁿ). Space: O(n). (Accepted approach: Backtracking with precedence fix.)
Expression Add Operators இல் பொதுவான தவறுகள் என்ன?
Numbers like '05' are invalid — skip multi-digit numbers starting with 0.