当前位置:网站首页>leetcode:494.数组中添加加减运算符得到指定值的所有方法
leetcode:494.数组中添加加减运算符得到指定值的所有方法
2022-06-28 03:06:00 【OceanStar的学习笔记】
题目来源
题目描述

题目解析
暴力递归
定义:对于数组arr[idx…]中所有的数字,搞出rest这个数,方法是多少。
int process(std::vector<int>&arr, int idx, int rest);
base case:
- 当没有数了,就没有选择了,这个时候看rest是否为0,如果为0,表示找到了一种方法,其他都是没有找到方法
普通情况:
- 就是base case之外的情况,也就是还有数可以选择
- 这个时候,我们要决定对arr[idx]做出选择,做出选择就会对rest造成影响。最后将剩下的递归给arr[idx+1…]
备忘录
对于:
int process(std::vector<int>&arr, int idx, int rest);
只要可变参数idx和rest固定了,那么process的返回值也就固定了
因此,我们只要用一个map指缓存起来,然后如果有,就直接去查就可以,没有就去计算
暴力递归改动态规划
优化
原问题等同于: 找到nums一个正子集P和一个负子集N,使得总和等于target。即
s u m ( P ) − s u m ( N ) = = t a r g e t sum(P) - sum(N) == target sum(P)−sum(N)==target
同时有:
s u m ( P ) + s u m ( N ) = = s u m sum(P) + sum(N) == sum sum(P)+sum(N)==sum
上面两式相加,得到
2 ∗ s u m ( P ) = = t a r g e t + s u m ( n u m s ) 2 * sum(P) == target + sum(nums) 2∗sum(P)==target+sum(nums)
其中target + sum(nums)必须>=0且为偶数,否则等式不可能成立。
则问题转换为:有一些物品,第i个物品的重量为nums[i], 背包的容量为sum§,问:有多少种方式将背包【恰好填满】
边栏推荐
猜你喜欢

数据库系列之InnoDB中在线DDL实现机制

云应用、服务的“5层”架构

友链须知

Simple implementation of cool GUI window based on WPF

可扩展数据库(上)

Scalable storage system (I)

View the SQL execution plan according to explain and optimize the SQL

开启创客教育造物学的领域

Solution to not displaying logcat logs during debugging of glory V8 real machine

17 `bs对象.节点名h3.parent` parents 获取父节点 祖先节点
随机推荐
Etcd database source code analysis -- network layer server rafthandler between clusters
JVM一:JVM入门以及Class文件认识
第二轮红队免费公开课来袭~明晚八点!
Sublime text 3 basic configuration tutorial
Arm development studio build compilation error
Li Kou daily question - day 29 -219 Duplicate Element II exists
力扣每日一题-第29天-523.在区间范围统计奇数数目
可扩展存储系统(上)
matlab习题 —— 矩阵的常规运算
启牛开的证券账户是安全的吗?如何开账户呢
17 `bs object Node name h3 Parent ` parents get parent node ancestor node
如何给Eclips自动添加作者,时间等…
Scalable storage system (I)
View the SQL execution plan according to explain and optimize the SQL
解决跨域
Hot! Yolov6's fast and accurate target detection framework is open source (with source code download)
Lost connection repair: make "hide and seek" nowhere to hide
Self use tool unity video player that monkeys can use
Win 10出现bitlocke恢复,蓝屏错误代码0x1600007e
Is it better for a novice to open a securities account? Is it safe to open a stock trading account