题目描述:
给定一个非负整数数组,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。
提示:
数组非空,且长度不会超过 20 。
初始的数组的和不会超过 1000 。
保证返回的最终结果能被 32 位整数存下。
解题思路:
暴力枚举,枚举全部情况然后统计等于目标值的个数共有多少,每个元素都有两种状态,+或-所以最多一共有2^n个情况,其中n为数组长度。所以我们不妨递归枚举全部情况。
代码:
public class LC494 {
//方法一:暴力,枚举
//时间复杂度O(2^N) 空间复杂度O(N) N为数组长度
int count = 0;//统计方法数
public int findTargetSumWays(int[] nums, int target) {
search(nums, 0, 0, target);
return count;
}
//递归枚举
private void search(int[] nums, int i, int sum, int target) {
if ( i == nums.length){
if (sum == target){
count++;
}
}else {
search(nums, i + 1, sum + nums[i], target);
search(nums, i + 1, sum - nums[i], target);
}
}
public static void main(String[] args) {
LC494 obj = new LC494();
System.out.println(obj.findTargetSumWays(new int[]{1, 1, 1, 1, 1}, 3));
}
}