zoukankan      html  css  js  c++  java
  • Leetcode: 494. Target Sum

    Description

    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

    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

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

    分析

    二分方法:
      输入数组最多长 20, 可以把数组拆为 2 个 长度为 10 的子数组。每个子数组中数字组合出的结果 会有 2**9 个。 将其中一个子数组排序。 然后依次遍历另外一个子数组,通过二分查找有序子数组获取答案。
    
    
    dp 方法:
      需要思考一下。。。
    
  • 相关阅读:
    方法的调用机制
    类的成员之二:方法
    类的成员之一:属性
    关键字static
    构造器
    this关键字
    递归方法(recursion)
    方法重载(二)
    GTID 跳过脚本
    mydumper 找不到libmysqlclient.so.20
  • 原文地址:https://www.cnblogs.com/tmortred/p/14436521.html
Copyright © 2011-2022 走看看