当前位置:网站首页>【LeetCode】494. Objective and (2 wrong questions)

【LeetCode】494. Objective and (2 wrong questions)

2022-06-11 11:49:00 Kaimar

0
1

  • Ideas
    The first feeling is the law of violence , But it will time out .
    Every nums It can only be used once , The object is nums[i], So is the value nums[i], The capacity of the backpack is target, Therefore, it can be analogized as 01 knapsack problem , The tricky thing is to add positive and negative questions .
    Refer to the explanation of the question
    S Namely target
    2
    3
    4
func sum(nums []int) int {
    
    sum := 0
    for _, v := range nums {
    
        sum += v
    }
    return sum
}

func abs(a int) int {
    
    return int(math.Abs(float64(a)))
}

func findTargetSumWays(nums []int, target int) int {
    
    nums_sum := sum(nums)
    if abs(target) > nums_sum {
    
        return 0
    }
    if (nums_sum + target) % 2 == 1 {
    
        return 0
    }
    bag := (target + nums_sum) / 2
    dp := make([]int, bag + 1)
    dp[0] = 1
    for i := 0; i < len(nums); i++ {
    
        for j := bag; j >= nums[i]; j-- {
    
            dp[j] += dp[j - nums[i]]
        }
    }
    return dp[bag]
}

5

原网站

版权声明
本文为[Kaimar]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/03/202203012150048674.html