LeetCode[377] Combination Sum IV
来源:互联网 发布:vscode 代码提示 编辑:程序博客网 时间:2024/06/05 21:52
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 = 4The 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?
动态规划。对于 sum = 0 的情况,只有一种可能,就是什么都不放。如果我们能求出 sum = target - i 有多少种情况(记为x),那么那么最后一步就只有一个选择:把 i 放进去。于是经过 target - i 到达 target 就有 x 种情况。所以我们只需要计算出到达 1~target-1 分别有多少种情况,target再各取所需即可
对于 folow up 中的可以有负数的情况,如果不限制每个元素用的次数,就有可能有无数种情况。
class Solution { public: int combinationSum4(vector<int>& nums, int target) { if (nums.size() == 0) return 0; vector<int> solution(target + 1, 0); solution[0] = 1; for (int i = 1; i <= target; i++) { for (int obj : nums) if (obj <= i) solution[i] += solution[i - obj]; } return solution[target]; }};
- LeetCode 377 Combination Sum IV
- LeetCode[377] Combination Sum IV
- LeetCode #377: Combination Sum IV
- Leetcode #377 Combination Sum IV
- LeetCode 377 Combination Sum IV
- 【Leetcode】Combination Sum IV
- [leetcode] Combination Sum IV
- Leetcode: Combination Sum IV
- LeetCode Combination Sum IV
- Leetcode Combination Sum IV
- LeetCode: Combination Sum IV
- LeetCode--Combination Sum IV
- leetcode 377 Combination Sum IV 动态规划
- 【LEETCODE】377- Combination Sum IV [Python]
- LeetCode No.377 Combination Sum IV
- LeetCode #377 - Combination Sum IV - Medium
- [377] Combination Sum IV
- Leetcode 377. Combination Sum IV
- HDU1756--判断点与多边形的相对位置
- {算法}论蒟蒻如何掌握ExGcd
- 数据结构上机测试2-1:单链表操作A
- 数据结构上机测试2-2:单链表操作B
- POJ Gold Balanced Lineup 3274 哈希
- LeetCode[377] Combination Sum IV
- 数据结构实验之链表六:有序链表的建立
- Class.getResource与Class.getClassLoader.getResource
- 数据结构实验之二叉树二:遍历二叉树
- 数据结构实验之二叉树二:遍历二叉树
- 自定义ImageView实现切图的无缝对接
- mybatis-字符串判断
- JAVA帮助文档全系列 JDK1.5 JDK1.6 JDK1.7 官方中英完整版下载
- 数据结构实验之二叉树的建立与遍历