Skip to content

Instantly share code, notes, and snippets.

@ylt6
Created February 25, 2020 15:13
Show Gist options
  • Save ylt6/fee8e43e9841d9483de0822ee32f13ec to your computer and use it in GitHub Desktop.
Save ylt6/fee8e43e9841d9483de0822ee32f13ec to your computer and use it in GitHub Desktop.
solution
class Solution:
def addOperators(self, num, target):
length = len(num)
ret = []
def rdfs(curr_index, curr_calculate, curr_expr):
if curr_index >= length:
if curr_calculate == target:
ret.append(curr_expr)
else:
for i in range(curr_index+1, len(num)+1):
if num[curr_index: i] == '00': break
n = int(num[curr_index: i])
print (f'curr_index: {curr_index}, curr_calculate: {curr_calculate}, curr_expr: {curr_expr}, n: {n}')
if n == 0:
rdfs(curr_index+i+1, eval(curr_expr+'0'), curr_expr+'0')
rdfs(i, curr_calculate + n, '{}+{}'.format(curr_expr, n))
rdfs(i, curr_calculate - n, '{}-{}'.format(curr_expr, n))
rdfs(i, eval('{}*{}'.format(curr_expr, n)), '{}*{}'.format(curr_expr, n))
rdfs(1, int(num[0]), str(num[0]))
return ret
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment