LeetCode-目标和

91 阅读1分钟

算法记录

LeetCode 题目:

  给你一个整数数组 nums 和一个整数 target 。向数组中的每个整数前添加 '+' 或 '-' ,然后串联起所有整数,可以构造一个 表达式 :


说明

一、题目

  通过上述方法构造的、运算结果等于 target 的不同 表达式 的数目。

二、分析

  • 简单的深度暴力求解, 按照二叉树的形式进行向下拓展.
class Solution {
    private int num;
    public void dfs(int[] nums, int count, int target, int now) {
        if(count == nums.length) {
            if(target == now) num++;
            return ;
        }
        dfs(nums, count + 1, target, now + nums[count]);
        dfs(nums, count + 1, target, now - nums[count]);
    }
    public int findTargetSumWays(int[] nums, int target) {
        dfs(nums, 0, target, 0);
        return num;
    }
}

总结

熟悉深度遍历方法。