Daily LeetCode 377. Combination Sum IV
https://leetcode.com/problems/combination-sum-iv/
Medium
问题描述:
Given an integer array with all positive numbers and no duplicates, find the number of possible combinations that add up to a positive integer target.
Example:
1 | nums = [1, 2, 3] |
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?
思路及代码:
给定一个nums数组和target,我们从nums中选数,找出所有组合,使得组合的和为target,最后返回组合个数。需要注意的是,不同排列顺序的组合被看作是不同的组合,需要重复计数。
我们可以反着思考这个问题,假设我们只需要再找一个数就能够使得和为target
,我们从nums数组中找任何一个小于target
的数即可。维护一维数组dp,dp[i]表示当target为i时,能够找到的组合数,dp[target] = sum(dp[target - nums[i]]), 0 <= i < len(nums), target >= nums[i]
。由于0只能够由0得到,因此dp[0]=1。在题目中给的例子中,dp[4] = dp[3] + dp[2] + dp[1]
。
代码:
1 | class Solution: |
给定数组中存在负数的情况:
当给定数组中存在负数时,组合数将是无穷无尽的。
例如,给定[1, -1, 2, -2],target为0时,我们能够找出无穷多个组合,来满足和为0这一条件。