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
    
    

     

  • 相关阅读:
    算术运算符
    短路运算
    基本运算符
    类型转换
    数据类型讲解
    关键字
    河北省重大技术需求征集八稿第六天
    河北省重大技术需求征集八稿第五天
    河北省重大技术需求征集八稿第四天
    河北省重大技术需求征集八稿第三天
  • 原文地址:https://www.cnblogs.com/immiao0319/p/13375960.html
Copyright © 2011-2022 走看看