zoukankan      html  css  js  c++  java
  • 494. Target Sum 494.目标总和

    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.

    思路:试试回溯:
    dfs(int[] nums, int S, )
    数量不知道该放在哪里
    其实为了凑出来一个和,参数里有个pos, 然后sum + nums[pos]就行了

    return ; //position到头之后,无论如何都要退出一下

    两个DFS都进行就行:

    dfs(nums, pos + 1, currentSum + nums[pos], S);
    dfs(nums, pos + 1, currentSum - nums[pos], S);
    class Solution {
        int count;
        
        public int findTargetSumWays(int[] nums, int S) {
            //cc
            if (nums == null || nums.length == 0)
                count = 0;
            
            //dfs
            dfs(nums, 0, 0, S);
            
            return count;
        }
        
        public void dfs(int[] nums, int pos, int currentSum, int S) {
            //exit
            if (pos == nums.length) {
                if (currentSum == S) 
                    count++;
                return ; //无论如何都要退出一下
            }
            
            dfs(nums, pos + 1, currentSum + nums[pos], S);
            dfs(nums, pos + 1, currentSum - nums[pos], S);
        }
    }
    View Code
    
    

     

  • 相关阅读:
    mysql 单表下的字段操作_查询
    mysql 表的操作
    mysql 单表下的字段操作
    mysql库的操作
    vim 复制&粘贴
    将系统剪贴板的内容粘贴到vim
    nc替代ping
    kali 将家目录下的中文文件名修改成英文
    Shiro反序列化漏洞检测、dnslog
    mac命令行切换python版本
  • 原文地址:https://www.cnblogs.com/immiao0319/p/13375960.html
Copyright © 2011-2022 走看看