FollowUp-进阶-377-Combination Sum IV

348 阅读1分钟

Follow up

  1. What if negative numbers are allowed in the given array?
  2. How does it change the problem?
  3. What limitation we need to add to the question to allow negative numbers?

答案

  1. 如果数组存在负数例如 [-2,2] ,且目标值为 0, 那么 [-2,2][-2,2,-2,2] 等均可,即答案是无限的。
  2. 动态规划不适合必须使用递归。因为当更新动态规划数组中的负数位置的值时,需要用到正数位置的值,而此时正数位置的值没有被更新。时间复杂度是 O(2^N) ,其中 N 是最大递归深度。
  3. 解决方法:
    • 声明数组中的数字仅仅能使用一次。
    • 或者,声明答案数组的最大长度。
    class Solution:
        def combinationSum4(self, nums, target, maxLen):
            memo = {}
            def helper(target, maxLen):
                if target == 0:
                    return 1
                if maxLen == 0:
                    return 0
                if (target, maxLen) in memo:
                    return memo[(target, maxLen)]
                ans = 0
                for x in nums:
                    ans += helper(target-x, maxLen-1)
                memo[(target, maxLen)] = ans;
                return ans;
            return helper(target, maxLen);
    

    相似题目