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.
    给定一个包含非负整数的列表 [a1, a2, ..., an],以及一个目标 S。你有两个符号 +-,对于每一个整数,你需要从这两个符号中选择一个作为这个数的符号。

    Find out how many ways to assign symbols to make sum of integers equal to target S.
    找出有多少种赋值的方式,使得赋值过后这些数的和等于 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.
    

    Constraints

    • The length of the given array is positive and will not exceed 20.
      给定的数组保证非空,且长度不超过 20。
    • The sum of elements in the given array will not exceed 1000.
      给定数组的元素和不超过 1000。
    • Your output answer is guaranteed to be fitted in a 32-bit integer.
      你的答案保证在 32 位整数的范围内。

    Solution

    由于此题只出现 + 和 -,没有其它符号,所以简单的深搜即可完成任务。代码如下:

    class Solution {
        private var result = 0
    
        fun findTargetSumWays(nums: IntArray, S: Int): Int {
            backtrack(nums, S, 0, 0)
            return result
        }
    
        private fun backtrack(nums: IntArray, s: Int, curSum: Int, curIndex: Int) {
            if (curIndex == nums.size ) {
                if (curSum == s) {
                    result++
                }
                return
            }
            // 当前数的符号取 +
            backtrack(nums, s, curSum + nums[curIndex], curIndex + 1)
            // 当前数的符号取 -
            backtrack(nums, s, curSum - nums[curIndex], curIndex + 1)
        }
    }
    
  • 相关阅读:
    递归--数字黑洞--蓝桥杯
    王、后问题
    递归--简单题--求二项式值
    有问题的题
    LeetCode----994. 腐烂的橘子「深度优先搜索」
    SpringBoot ---- MyBatis Plus 入门
    Spring Boot ---- 整合 MyBatis (注解方式)
    Android笔记
    LeetCode----跳跃游戏Ⅱ「动态规划」
    2020年米哈游秋季招聘程序 B卷编程题
  • 原文地址:https://www.cnblogs.com/zhongju/p/14023637.html
Copyright © 2011-2022 走看看