您好我有以下问题需要实施:
我有两个数组 n 整数数组和 n - 1 操作数组
integers[n]
// n整数 operations[n - 1]
// n - 1次操作(例如+ - * /) 数字数组是固定的,而运算符数组可用于任何排列以获得最大值(谢谢@ grek40 )
示例1:
给定整数数组:1 2 7 5 1 2
和操作数组:+ + + + *
我想找到最大相邻乘积和减法除法1+2+7*5+1+2 = 41
示例2:
给定整数数组:1 3 5 6 9 10 12 14
和操作数组:+ + * * - / /
我想找到最大相邻乘积和减法除法1-3/5/6+9+10*12*14 = 1689.9
我是动态编程的初学者。我无法弄清楚以下问题的递归关系。
任何人都可以提出建议吗?
谢谢!
我尝试使用Enumeration方法,时间复杂度为n!
for operators in allOperators:
op = list(operators)
op.append(' ')
operation = ""
for i, number in enumerate(inputNumbers):
count += 1
operation += number + op[i]
output = eval(operation)
if output > maxOutput:
maxOutput = output
答案 0 :(得分:1)
import functools
test1 = (1, 2, 7, 5, 1, 2)
test2 = (1, 3, 5, 6 ,9 ,10, 12, 14)
@functools.lru_cache()
def BaseSolution(nums, add, sub, mul, div, length):
if add<0 or sub<0 or mul<0 or div<0 or length<0:
return float("-inf")
if length == 0:
return nums[length]
else:
return max(
BaseSolution(nums, add-1, sub, mul, div, length-1) + nums[length],
BaseSolution(nums, add, sub-1, mul, div, length-1) - nums[length],
MulOrDivSolution(nums, add, sub, mul-1, div, length-1, '*'+str(nums[length])),
MulOrDivSolution(nums, add, sub, mul, div-1, length-1, '/'+str(nums[length])),
)
def MulOrDivSolution(nums, add, sub, mul, div, length, lzayVal):
if add<0 or sub<0 or mul<0 or div<0 or length<0:
return float("-inf")
if length == 0:
return eval( str(nums[length])+lzayVal)
else:
return max(
BaseSolution(nums, add-1, sub, mul, div, length-1) + eval( str(nums[length])+lzayVal),
BaseSolution(nums, add, sub-1, mul, div, length-1) - eval( str(nums[length])+lzayVal),
MulOrDivSolution(nums, add, sub, mul-1, div, length-1, '*'+str(nums[length])+lzayVal),
MulOrDivSolution(nums, add, sub, mul, div-1, length-1, '/'+str(nums[length])+lzayVal),
)
if __name__ == '__main__':
print(BaseSolution(test1,4,0,0,1,5))
print(BaseSolution(test2,2,1,2,2,7))
答案 1 :(得分:0)
您可以采用与此问题类似的方法:
Given a list of integer numbers, a list of symbols [+,-,*,/] and a target number N,
唯一不同的是它谈到匹配数字N,你可以找到最大总和。
这里的想法是生成运算符的组合,只要数组的长度。
map<operator, count>
Getresult(expression)
std::next_permutation:
current_max
,expression_max
追踪最多current_max
和expression_max