首先需要明白以下区别,我们才能更好地用C++做对leetcode 中的377题目。
int和long区别如下:
占内存长度不同和取值范围不同。
32位系统:long是4字节32位,int是4字节32位。
64位系统:long是8字节64位,int是4字节32位。
注意事项:
1、long类型的范围是:-9223372036854775808~9223372036854775807。
2、如果只用正数可以考虑用unsigned long long范围是:0~18446744073709551615。
对象类型:
long、int占多少字节,得看计算机cpu是多少位的。16位机器上,int2字节,long4字节,32位机器上二者都是4字节,64位机器上,int4字节,long8字节
题目:
给定一个由正整数组成且不存在重复数字的数组,找出和为给定目标正整数的组合的个数。
示例:
nums = [1, 2, 3] target = 4 所有可能的组合为: (1, 1, 1, 1) (1, 1, 2) (1, 2, 1) (1, 3) (2, 1, 1) (2, 2) (3, 1) 请注意,顺序不同的序列被视作不同的组合。 因此输出为 7。
进阶:
如果给定的数组中含有负数会怎么样?
问题会产生什么变化?
我们需要在题目中添加什么限制来允许负数的出现?
方法一:利用递归完成(时间超时)
class Solution {
public:
int combinationSum4(vector<int>& nums, int target) {
return solutionSum(nums, target);
}
int solutionSum(vector<int>& nums, int target)
{
if(target == 0)
{
return 1;
}
int count = 0;
for(int i = 0; i < nums.size(); ++i)
{
if(target >= nums[i])
{
count = count + combinationSum4(nums, target - nums[i]);
}
}
return count;
}
方法二:利用动态规划
class Solution {
public:
int combinationSum4(vector<int>& nums, int target) {
vector<long> dp(target + 1);//必须使用long,使用int的话,会报错,小伙伴可以尝试一下
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];
if(dp[i]>INT_MAX)dp[i]%=INT_MAX;
}
}
return dp.back();
}
};