图(dfs)494. Target Sum[middle]
来源:互联网 发布:鱼骨标本淘宝 编辑:程序博客网 时间:2024/06/06 03:58
题目:
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.
给一串数,一个结果S,在数中间使用+ -运算得到 S
分析:
直觉就是,递归,对一个数,选择+和选择- 分别递归,递归基就是算完了全部的数。
代码:
class Solution {public: void sum(vector<int>& nums, int& he, int S, int size, int& all) {if (size == nums.size() && he == S) { //满足条件的S,计数器加一all++;}if (size < nums.size()) { //选择 - ,递归he += -nums[size];sum(nums, he, S, size+1, all);he -= -nums[size]; //选择 + ,递归he += nums[size];sum(nums, he, S, size + 1, all);he -= nums[size];}} int findTargetSumWays(vector<int>& nums, int S) { int all = 0;int size = 0;int he = 0;sum(nums, he, S, size, all);return all; }};
递归刚开始接触时并不是很好写的,这道题解法寥寥几句,但是清楚、正确地写出来也不容易……
0 0
- 图(dfs)494. Target Sum[middle]
- DFS——Target Sum
- 494. Target Sum(第十一周)
- 494. Target Sum(动态规划)
- LeetCode 494. Target Sum
- [LeetCode]494. Target Sum
- 494. Target Sum
- [leetcode]494. Target Sum
- 494. Target Sum
- Leetcode 494. Target Sum
- 494. Target Sum -Medium
- 494. Target Sum
- Leetcode-494. Target Sum
- 494. Target Sum
- Leetcode 494. Target Sum
- 494. Target Sum
- leetcode-494. Target Sum
- 494. Target Sum
- opencv学习之快速对图像的像素进行操作 opencv 实战
- CCF CSP试题 201612-3 权限查询
- unity自带寻路组件navigation使用记录(一)最菜鸟
- java File 通过递归方式删除文件和目录
- 《Objective-C编程全解》 读书笔记 第十章 范畴
- 图(dfs)494. Target Sum[middle]
- win10下git 服务器的搭建
- 用IntelliJ IDEA搭建第一个SpringBoot例子
- Solr.NET快速入门(八)【多核多实例,映射验证】
- 腾讯云多维活体检测,让人脸识别更安全
- opencv学习之图像滤波
- 环境准备
- 【Python】Mac下Sublime Text3配置Python3开发环境
- MapReduce中实现Join操作