给你一个整数数组 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
题解:
直接暴力搜索即可
class Solution {
static int count = 0;
public int findTargetSumWays(int[] nums, int target) {
back(nums,0,target);
return count;
}
public void back(int[] nums,int index,int target){
if(index==nums.length){
if(target==0){
count++;
}
return;
}
back(nums,index+1,target+nums[index]);
back(nums,index+1,target-nums[index]);
}
}
题解:记忆化搜索
class Solution {
public int findTargetSumWays(int[] nums, int t) {
return dfs(nums, t, 0, 0);
}
//记忆化存储
Map<String, Integer> cache = new HashMap<>();
int dfs(int[] nums, int t, int u, int cur) {
String key = u + "_" + cur;
//如果该点已经被搜索过
if (cache.containsKey(key)) {
//直接返回该点搜索过的结果
return cache.get(key);
}
//如果到达递归终点
if (u == nums.length) {
//向记忆容器中放入搜索的最终结果,如果搜索到答案,value值为1,否则为0
cache.put(key, cur == t ? 1 : 0);
//返回搜索到的结果
return cache.get(key);
}
//获取+答案
int left = dfs(nums, t, u + 1, cur + nums[u]);
//获取-答案
int right = dfs(nums, t, u + 1, cur - nums[u]);
//放入搜索结果
cache.put(key, left + right);
return cache.get(key);
}
}