(1)由于a<=b<=c 使用排序,将数组从下到大排序,这样递归的结果永远都是啊a<=b<=c;
(2)递归+回溯+剪支
class Solution { public: void gen(int i,set<vector<int>> &res,vector<int> &temp,vector<int> &num,int sum,int target,vector<vector<int>> &result){ //剪支 if(i>=num.size()||temp.size()>3) return; if(temp.size()==3&&sum!=target) return; sum+=num[i]; temp.push_back(num[i]); //边界条件 if(temp.size()==3&&sum==target&&res.find(temp)==res.end()){ result.push_back(temp); res.insert(temp); //return; } gen(i+1,res,temp,num,sum,target,result); //回溯 sum-=num[i]; temp.pop_back(); gen(i+1,res,temp,num,sum,target,result); } vector<vector<int> > threeSum(vector<int> &num) { vector<vector<int>> result; set<vector<int>> res; if(num.size()==0) return result; vector<int> temp; //排序 sort(num.begin(),num.end()); gen(0,res,temp,num,0,0,result); return result; } };