leetCode---Target Sum
来源:互联网 发布:大数据平台服务目录 编辑:程序博客网 时间:2024/06/06 03:02
一. 题目:Target Sum
You are given a list of non-negative integers, a1, a2, ..., an, and a target, S. Now you have 2 symbols+
and-
. For each integer, you should choose one from+
and-
as its new symbol.
Find out how many ways to assign symbols to make sum of integers equal to target S.
Example 1:
Input: nums is [1, 1, 1, 1, 1], S is 3. Output: 5Explanation: -1+1+1+1+1 = 3+1-1+1+1+1 = 3+1+1-1+1+1 = 3+1+1+1-1+1 = 3+1+1+1+1-1 = 3There are 5 ways to assign symbols to make the sum of nums be target 3.
Note:
- The length of the given array is positive and will not exceed 20.
- The sum of elements in the given array will not exceed 1000.
- Your output answer is guaranteed to be fitted in a 32-bit integer.
二. 思路分析
这道题给了我们一个数组,和一个目标值,让我们给数组中每个数字加上正号或负号,然后求和要和目标值相等,求有多少中不同的情况。对于这种求多种情况的问题,最想到的方法使用递归来做,尝试每次添加“+”或者“-”,当count为nums数组的大小的时候,判断sum与S是否相等,如果相等就result++。我们从第一个数字,调用递归函数,在递归函数中,分别对目标值进行加上当前数字调用递归,和减去当前数字调用递归,这样会涵盖所有情况。参见代码如下:
class Solution {public: int result; int findTargetSumWays(vector<int>& nums, int S) { rec(0, 0, nums, S); return result; } void rec(int sum, int count, vector<int>& nums, int S) { if(count == nums.size()) { if(sum == S) result++; return ; } rec(sum + nums[count], count + 1, nums, S); rec(sum - nums[count], count + 1, nums, S); }};
0 0
- LeetCode 494. Target Sum
- [LeetCode]494. Target Sum
- [leetcode]494. Target Sum
- Leetcode 494. Target Sum
- LeetCode: Target Sum
- leetcode[494]:Target Sum
- leetCode---Target Sum
- Leetcode-494. Target Sum
- LeetCode 494:Target Sum
- leetcode 494 Target sum
- Leetcode 494. Target Sum
- leetcode-494. Target Sum
- [LeetCode OJ]Target Sum
- leetcode:494. Target Sum
- (LeetCode) 494. Target Sum
- LeetCode 494. Target Sum
- [LeetCode] Target Sum
- LeetCode—Target Sum
- JVM 的类文件结构
- Hdu1051 Wooden Sticks
- 类和对象
- 基于SpringMVC框架实现客服聊天
- 蓝桥杯ALGO-39——算法训练 数组排序去重
- leetCode---Target Sum
- 螺旋矩阵
- Hibernate的核心对象关系映射
- easyui里的layout折叠显示标题
- Android蓝牙通信——安卓蓝牙obtainMessage数据传输部分数据丢失乱序问题
- 搭建cordova环境重要注意事项
- ss
- java 控制访问权限
- Square Coins