494.目标和
题目:给定一个非负整数数组,a1, a2, …, an, 和一个目标数,S。现在你有两个符号 + 和 -。对于数组中的任意一个整数,你都可以从 + 或 -中选择一个符号添加在前面。
返回可以使最终数组和为目标数 S 的所有添加符号的方法数。
示例:
输入:nums: [1, 1, 1, 1, 1], S: 3
输出:5
解释:
-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
一共有5种方法让最终目标和为3。
class Solution {
public:
int findTargetSumWays(vector<int>& nums, int S) {
const int sum = std::accumulate(nums.begin(), nums.end(), 0);
//剪枝
if(sum < std::abs(S)) return 0;
int ans = 0;
dfs(nums, 0, S, ans);
return ans;
}
private:
void dfs(const vector<int>& nums, int d, int S, int & ans)
{
if(d == nums.size())
{
if(S == 0) ans++;
return;
}
//S-nums[d] 相当于加号
dfs(nums, d+1, S-nums[d], ans);
//S+nums[d] 相当于减号
dfs(nums, d+1, S+nums[d], ans);
}
};
时间复杂度:O(2n) 空间复杂度:O(n)
本文介绍了一种算法,用于计算给定整数数组通过选择+或-符号进行操作后,使其和等于目标值S的不同方法数。时间复杂度为O(2n),空间复杂度为O(n)。通过递归实现的dfs函数展示了如何遍历所有可能的组合来解决这个问题。

257

被折叠的 条评论
为什么被折叠?



