Given a string of numbers and operators, return all possible results from computing all the different possible ways to group numbers and operators. The valid operators are +, - and *.
Example 1:
Input: “2-1-1”
Output: [0, 2]
Explanation:
((2-1)-1) = 0
(2-(1-1)) = 2
Example 2:
Input: “2*3-4*5”
Output: [-34, -14, -10, -10, 10]
Explanation:
(2*(3-(4*5))) = -34
((2*3)-(4*5)) = -14
((2*(3-4))*5)= -10
(((2*3)-4)*5) = 10
分析:
题目的意思是给出不同位置加括号后的结果。
没思路,借鉴讨论区的。注意输入是字符串。。
采用分治策略。
code:
def diff_add(input):
if input.isdigit():
return [int(input)]
res = []
for i in range(len(input)):
if input[i] in "-+*":
res1 = diff_add(input[:i])
res2 = diff_add(input[i+1:])
for n in res1:
for m in res2:
res.append(cal(n, m, input[i]))
return res
def cal(n, m, op):
if op == '+':
return n + m
elif op == '-':
return n - m
else:
return n * m
分治策略的思想:将一个很难解决的大问题,分成相同的子问题,以便各个击破,从而得到大问题的解。
适用情况:
- 该问题缩小到一定规模可以容易解决;
- 该问题可以分解成若干规模较小的相同问题,即该问题具有最优子结构性质;
- 利用该问题分解出的子问题可以合并为该问题的解;(最主要的特征)
经典问题:
- 二分法
- 快速排序、归并排序
- 大整数乘法
参考文献:
https://www.cnblogs.com/steven_oyj/archive/2010/05/22/1741370.html