本文共 2076 字,大约阅读时间需要 6 分钟。
class Solution {public: void threeSum(int step, int sum, vector & path, vector>& ans, const vector & num, vector & used) { if(path.size() == 3) { ans.push_back(path); return; } if(step >= num.size()) return; //1. not choose threeSum(step+1, sum, path, ans, num, used); //2. choose if(step != 0 && num[step] == num[step-1] && !used[step-1]) return;//avoid same combination if(path.size() == 2 && sum+num[step] != 0) return;//sum not equal to zero used[step] = true; path.push_back(num[step]); threeSum(step+1, sum+num[step], path, ans, num, used); used[step] = false; path.pop_back(); } vector > threeSum(vector &num) { // Start typing your C/C++ solution below // DO NOT write int main() function if(num.size() == 0) return vector >(); sort(num.begin(), num.end()); vector path; vector > ans; vector used(num.size(), false); threeSum(0, 0, path, ans, num, used); return ans; }};
second time
class Solution {public: vector> threeSum(vector &num) { // Start typing your C/C++ solution below // DO NOT write int main() function sort(num.begin(), num.end()); vector > ans; for(int i = 0; i < num.size(); ++i) { if(i != 0 && num[i] == num[i-1]) continue; int left = i+1; int right = num.size()-1; vector triplet(3); while(left < right) { int sum = num[left]+num[right]+num[i]; if(sum > 0) right--; else if(sum < 0) left++; else { triplet[0] = num[i], triplet[1] = num[left], triplet[2] = num[right]; ans.push_back(triplet); //break; int oldLeftNum = num[left]; while(left < num.size() && num[left] == oldLeftNum) left++; } } } return ans; }};
转载地址:http://qaxti.baihongyu.com/