目标和

题目:目标和

问题描述:

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

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

解决思路:

直接使用 dfs 进行递归即可。

解决代码:


class Solution {
    private int count = 0;
    public int findTargetSumWays(int[] nums, int S) {
        dfs(nums, 0, 0, S);
        return count;
    }

    private void dfs(int[] nums, int index, int sum, int target) {
        if(index == nums.length) {
            if(sum == target) {
                count++;
            }
        } else {
            dfs(nums, index+1, sum-nums[index], target);
            dfs(nums, index+1, sum+nums[index], target);
        }
    }

}

原文地址:https://www.cnblogs.com/syhyfh/p/13254136.html