zoukankan      html  css  js  c++  java
  • 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.
    

    Note:

    1. The length of the given array is positive and will not exceed 20.
    2. The sum of elements in the given array will not exceed 1000.
    3. Your output answer is guaranteed to be fitted in a 32-bit integer.

     方法1:递归暴力解决(效果较差,仅比6%的人快)

    class Solution {
    public:
    
        void help(vector<int>& nums, int i, int sum, int target, int &count)
        {
            if (i + 1 == nums.size() && sum == target)count++;
            else if (i + 1 == nums.size() && sum != target)return ;
            else
            {
                help(nums, i + 1, sum + nums[i + 1], target, count);
                help(nums, i + 1, sum - nums[i + 1], target, count);
            }
        }
        int findTargetSumWays(vector<int>& nums, int S) {
            if (nums.size() < 1) return 0;
            int count = 0;
            help(nums, 0, nums[0], S, count);
            help(nums, 0, -nums[0], S, count);
            return count;
        }
    };

    方法2:动态规划(没看懂,待学习)

  • 相关阅读:
    VS2010下配置CxImage
    Visual Studio 2010 开发配置
    主机屋使用感受
    Web开发者必备的20款超赞jQuery插件
    自动页面居中
    jQuery+CSS打造的网页背景颜色切换效果
    小按钮,大学问
    【网站开发必备】——12款响应式 Lightbox(灯箱)效果插件
    修正 IE 的双倍页边距 bug
    a>b?a:b
  • 原文地址:https://www.cnblogs.com/qiang-wei/p/12271263.html
Copyright © 2011-2022 走看看