首先需要明白以下區別,我們才能更好地用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(); } };