494. Target Sum 添加标点符号求和

[抄题]:

You are given a list of non-negative integers, a1, a2, ..., an, and a target, S. Now you have 2 symbols + and -. For each integer, you should choose one from + and - as its new symbol.

Find out how many ways to assign symbols to make sum of integers equal to target S.

Example 1:

Input: nums is [1, 1, 1, 1, 1], S is 3. 
Output: 5
Explanation: 

-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

There are 5 ways to assign symbols to make the sum of nums be target 3.

 [暴力解法]:

时间分析:

空间分析:

 [优化后]:

时间分析:

空间分析:

[奇葩输出条件]:

[奇葩corner case]:

[思维问题]:

种类:看似用DP,但是其实很麻烦

[一句话思路]:

用DFS也能求出种类

[输入量]:空: 正常情况:特大:特小:程序里处理到的特殊情况:异常情况(不合法不合理的输入):

[画图]:

[一刷]:

  1. 理解一下退出条件:符合sum = target就count++,达到长度要求就退出

[二刷]:

[三刷]:

[四刷]:

[五刷]:

  [五分钟肉眼debug的结果]:

[总结]:

[复杂度]:Time complexity: O(每一个都试试加减法 2^n) Space complexity: O(1)

[英文数据结构或算法,为什么不用别的数据结构或算法]:

[算法思想:递归/分治/贪心]:递归

[关键模板化代码]:

数组名、目标、位置、当前和

public void dfs(int[] nums, int target, int pos, int sum) {
        //exit
        if (pos == nums.length) {
            if (sum == target) count++;
                return ; 
        }

[其他解法]:

[Follow Up]:

[LC给出的题目变变变]:

282. Expression Add Operators

 [代码风格] :

class Solution {
    int count = 0;
    
    public int findTargetSumWays(int[] nums, int S) {
        //cc
        if (nums == null || nums.length == 0) return 0;
        
        //dfs
        dfs(nums, S, 0, 0);
        
        //return
        return count;
    }
    
    public void dfs(int[] nums, int target, int pos, int sum) {
        //exit
        if (pos == nums.length) {
            if (sum == target) count++;
                return ; 
        }
        
        //dfs
        dfs(nums, target, pos + 1, sum + nums[pos]);
        dfs(nums, target, pos + 1, sum - nums[pos]);
    }
}
View Code

猜你喜欢

转载自www.cnblogs.com/immiao0319/p/9038326.html
今日推荐