494:目标和

This commit is contained in:
huangge1199 2021-06-07 10:11:26 +08:00
parent db72510308
commit a303c8f73c
3 changed files with 124 additions and 2 deletions

View File

@ -0,0 +1,80 @@
//给你一个整数数组 nums 和一个整数 target
//
// 向数组中的每个整数前添加 '+' '-' 然后串联起所有整数可以构造一个 表达式
//
//
// 例如nums = [2, 1] 可以在 2 之前添加 '+' 1 之前添加 '-' 然后串联起来得到表达式 "+2-1"
//
//
// 返回可以通过上述方法构造的运算结果等于 target 的不同 表达式 的数目
//
//
//
// 示例 1
//
//
//输入nums = [1,1,1,1,1], target = 3
//输出5
//解释一共有 5 种方法让最终目标和为 3
//-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 = 3
//
//
// 示例 2
//
//
//输入nums = [1], target = 1
//输出1
//
//
//
//
// 提示
//
//
// 1 <= nums.length <= 20
// 0 <= nums[i] <= 1000
// 0 <= sum(nums[i]) <= 1000
// -1000 <= target <= 100
//
// Related Topics 深度优先搜索 动态规划
// 👍 718 👎 0
package leetcode.editor.cn;
//494:目标和
public class TargetSum {
public static void main(String[] args) {
//测试代码
Solution solution = new TargetSum().new Solution();
// System.out.println(solution.findTargetSumWays(new int[]{1, 1, 1, 1, 1}, 3));
System.out.println(solution.findTargetSumWays(new int[]{1}, 1));
}
//力扣代码
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
int count = 0;
public int findTargetSumWays(int[] nums, int target) {
sum(nums, target, nums.length - 1);
return count;
}
private void sum(int[] nums, int target, int index) {
if (index == -1) {
if (target == 0) {
count++;
}
} else {
sum(nums, target + nums[index], index - 1);
sum(nums, target - nums[index], index - 1);
}
}
}
//leetcode submit region end(Prohibit modification and deletion)
}

View File

@ -0,0 +1,43 @@
<p>给你一个整数数组 <code>nums</code> 和一个整数 <code>target</code></p>
<p>向数组中的每个整数前添加 <code>'+'</code><code>'-'</code> ,然后串联起所有整数,可以构造一个 <strong>表达式</strong> </p>
<ul>
<li>例如,<code>nums = [2, 1]</code> ,可以在 <code>2</code> 之前添加 <code>'+'</code> ,在 <code>1</code> 之前添加 <code>'-'</code> ,然后串联起来得到表达式 <code>"+2-1"</code></li>
</ul>
<p>返回可以通过上述方法构造的、运算结果等于 <code>target</code> 的不同 <strong>表达式</strong> 的数目。</p>
<p> </p>
<p><strong>示例 1</strong></p>
<pre>
<strong>输入:</strong>nums = [1,1,1,1,1], target = 3
<strong>输出:</strong>5
<strong>解释:</strong>一共有 5 种方法让最终目标和为 3 。
-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 = 3
</pre>
<p><strong>示例 2</strong></p>
<pre>
<strong>输入:</strong>nums = [1], target = 1
<strong>输出:</strong>1
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li><code>1 <= nums.length <= 20</code></li>
<li><code>0 <= nums[i] <= 1000</code></li>
<li><code>0 <= sum(nums[i]) <= 1000</code></li>
<li><code>-1000 <= target <= 100</code></li>
</ul>
<div><div>Related Topics</div><div><li>深度优先搜索</li><li>动态规划</li></div></div>\n<div><li>👍 718</li><li>👎 0</li></div>

File diff suppressed because one or more lines are too long