演算法程式設計-求陣列中和為0的最長子串(非連續最長子串+連續最長子串)
阿新 • • 發佈:2018-12-15
輸入:int 型陣列由正數、負數、0組成
輸出:最長和為0的子序列
分析:
1)連續子串
2)非連續子串
void findTargetLen1(vector<int>nums,int sum,int len,int& maxLen,int start) { //非連續子串長度 if (start == nums.size()) return; if (sum == 0) maxLen = max(len, maxLen);//求和為0最大子串長度 for (int i =start;i<nums.size();i++) { findTargetLen1(nums, sum - nums[i], len - 1, maxLen, start+1);//減掉這個數 findTargetLen1(nums, sum, len, maxLen, start+1);//不減這個數 } } int findTargetLen2(vector<int>nums) { //連續最長子串 int res = 0; for (int i = 1; i < nums.size(); i++) { if (nums[i] == 0 || nums[i - 1] == 0) res = 1; nums[i] = nums[i] + nums[i - 1]; } for (int i=nums.size()-1;i>0;i--) for (int j = i - 1; j >= 0; j--) if (nums[j] == nums[i])res = max(res, i - j); return res; } int main() { int n; cin >> n; int sum = 0; vector<int>nums(n); for (int i = 0; i < n; i++) { cin >> nums[i]; sum += nums[i]; } int len = nums.size(); int maxlen = 0; findTargetLen1(nums, sum, len, maxlen, 0); cout << maxlen << endl; cout << findTargetLen2(nums) << endl; system("pause"); return 0; }
歡迎交流