leetcode494-目标和

原题

给定一个非负整数数组,a1, a2, …, an, 和一个目标数,S。现在你有两个符号 + 和 -。对于数组中的任意一个整数,你都可以从 + 或 -中选择一个符号添加在前面。

返回可以使最终数组和为目标数 S 的所有添加符号的方法数。

示例 1:

输入: 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。

注意:

  1. 数组非空,且长度不会超过20。
  2. 初始的数组的和不会超过1000。
  3. 保证返回的最终结果能被32位整数存下。

解法

思想

DFS比较暴力,追求时间快可以用01背包问题的动态规划思想,以后更。

代码

class Solution {
    public int[] numsArray;
    public int target;
    public int findTargetSumWays(int[] nums, int S) {
        numsArray = nums;
        target = S;
        return dfs(0,0);
    }
    public int dfs(int index,int sum){
        if(index == numsArray.length){
            if(sum == target) return 1;
            else return 0;
        }
        return dfs(index+1,sum+numsArray[index])+dfs(index+1,sum-numsArray[index]);
    }
}

原创文章,作者:彭晨涛,如若转载,请注明出处:https://www.codetool.top/article/leetcode494-%e7%9b%ae%e6%a0%87%e5%92%8c/

发表回复

登录后才能评论