377. Combination Sum IV
  rEZj93RghFYQ 2023年11月02日 18 0


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:

nums = [1, 2, 3]
target = 4

The possible combination ways are:
(1, 1, 1, 1)
(1, 1, 2)
(1, 2, 1)
(1, 3)
(2, 1, 1)
(2, 2)
(3, 1)

Note that different sequences are counted as different combinations.

Therefore the output is 7.

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?

class Solution {
public int combinationSum4(int[] nums, int target) {
if (nums.length == 0)
return 0;
Arrays.sort(nums);
int[] dp = new int[target+1];
dp[0] = 1;

for (int i = 1; i <= target; i++) {
for (int j = 0; j < nums.length; j++) {
if (i - nums[j] >= 0) dp[i] += dp[i - nums[j]];
else break;
}
}
return


【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月08日 0

暂无评论

推荐阅读
  rEZj93RghFYQ   2023年11月02日   19   0   0 i++leetcode-java
  dUbcXj9lnElT   2023年11月02日   28   0   0 #includei++c++
  dUbcXj9lnElT   2023年11月02日   19   0   0 #include连通块i++
rEZj93RghFYQ
作者其他文章 更多
最新推荐 更多