Combination Sum IV
来源:互联网 发布:智能电视直播软件2017 编辑:程序博客网 时间:2024/06/16 05:16
题目大意:
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?
题目意思:
给定一个无重复的正整数数组,计算得到一个目标正整数的所有可能组合方式的个数。
测试用例见题目描述。
注意不同的序列顺序应当视为不同的组合。
进一步思考:
如果数组中允许包含负数时应当怎样处理?
这会使问题作出怎样的变动?
如果允许负数需要对问题新增怎样的限制条件?
解题思路:
开始是用DFS来做,出现超时情况。因为用递归+回溯的方法其实是用穷举的方式对所有的数字进行遍历,那就会出现超时的情况发生。最后使用动态规划来做,需要一个一维数组dp,其中dp[i]表示目标数为i的解的个数,然后从1遍历到target,对于每一个数i,遍历nums数组,如果i>=x, dp[i] += dp[i - x]。比如说对于[1,2,3] 4,这个例子,当在计算dp[3]的时候,3可以拆分为1+x,而x即为dp[2],3也可以拆分为2+x,此时x为dp[1],3同样可以拆为3+x,此时x为dp[0],把所有的情况加起来就是组成3的所有情况了。
代码如下:
class Solution {
public:
int combinationSum4(vector<int>& nums, int target) {
vector<int> dp(target + 1);
dp[0] = 1;
for (int i = 1; i <= target; ++i) {
for (auto a : nums) {
if (i >= a) dp[i] += dp[i - a];
}
}
return dp.back();
}
};
如果target远大于nums数组的个数的话,上面的算法可以做适当的优化,先给nums数组排个序,然后从1遍历到target,对于i小于数组中的数字x时,直接break掉,因为后面的数更大,其余地方不变,代码如下:
class Solution {
public:
int combinationSum4(vector<int>& nums, int target) {
vector<int> dp(target + 1);
dp[0] = 1;
sort(nums.begin(), nums.end());
for (int i = 1; i <= target; ++i) {
for (auto a : nums) {
if (i < a) break;
dp[i] += dp[i - a];
}
}
return dp.back();
}
};
- 【Leetcode】Combination Sum IV
- [leetcode] Combination Sum IV
- 377. Combination Sum IV
- 377. Combination Sum IV
- Combination Sum IV
- 377. Combination Sum IV
- 377. Combination Sum IV
- Combination Sum IV
- Combination Sum IV
- [377] Combination Sum IV
- 377. Combination Sum IV
- 377. Combination Sum IV
- Leetcode: Combination Sum IV
- leetcode_377 Combination Sum IV
- Combination Sum IV
- LeetCode Combination Sum IV
- Combination Sum IV
- 377. Combination Sum IV
- 傅盛认知三部曲之三:战略就是格局+破局
- 名字的漂亮度
- NYOJ 448 寻找最大数
- nginx源码浅析--编译前准备configure简介
- Picasso的简单实用
- Combination Sum IV
- Linux socket浅谈
- SQLyong 和 MySQL中文乱码解决办法
- C++从零实现BP神经网络
- MySQL高级查询---连接查询实例
- [bzoj4553][Tjoi2016&Heoi2016]序列 cdq分治
- java 基础知识2 --数组
- Glide加载图片的简单实用
- TREAP示例代码(排序)