1+ """
2+ """
3+ class Solution :
4+ def addOperators (self , num : str , target : int ) -> List [str ]:
5+ if len (num ) == 0 :
6+ return []
7+
8+ self .ans = []
9+
10+ def dfs (idx , path ):
11+ if idx == len (num ) - 1 :
12+ path += num [idx ]
13+ if eval (path ) == target :
14+ self .ans .append (path )
15+ return
16+
17+ dfs (idx + 1 , path + num [idx ] + "+" )
18+ dfs (idx + 1 , path + num [idx ] + "-" )
19+ dfs (idx + 1 , path + num [idx ] + "*" )
20+ if (num [idx ] != '0' or (path and path [- 1 ] not in ['-' ,'+' ,'*' ] and num [idx ]== '0' )):
21+ dfs (idx + 1 , path + num [idx ])
22+
23+
24+ dfs (0 , "" )
25+
26+ return self .ans
27+
28+ class Solution :
29+ def addOperators (self , num : 'str' , target : 'int' ) -> 'List[str]' :
30+
31+ ans = []
32+
33+ def dfs (i , prev , cur , val , eq ):
34+ if i == len (num ):
35+ if val == target and cur == 0 :
36+ ans .append ("" .join (eq [1 :]))
37+ return
38+
39+ cur = cur * 10 + int (num [i ])
40+ str_op = str (cur )
41+
42+ if cur > 0 :
43+ dfs (i + 1 , prev , cur , val , eq )
44+
45+ dfs (i + 1 , cur , 0 , val + cur , eq + "+" + str_op )
46+
47+ if eq :
48+ dfs (i + 1 , - cur , 0 , val - cur , eq + '-' + str_op )
49+ dfs (i + 1 , cur * prev , 0 , val - prev + (cur * prev ), eq + '*' + str_op )
50+
51+
52+ dfs (0 ,0 ,0 ,0 ,"" )
53+
54+ return ans
55+
0 commit comments