Follow up
- What if negative numbers are allowed in the given array?
- How does it change the problem?
- What limitation we need to add to the question to allow negative numbers?
答案
- 如果数组存在负数例如
[-2,2],且目标值为0, 那么[-2,2],[-2,2,-2,2]等均可,即答案是无限的。 - 动态规划不适合必须使用递归。因为当更新动态规划数组中的负数位置的值时,需要用到正数位置的值,而此时正数位置的值没有被更新。时间复杂度是
O(2^N),其中N是最大递归深度。 - 解决方法:
- 声明数组中的数字仅仅能使用一次。
- 或者,声明答案数组的最大长度。
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);相似题目