自己写的比较差的,时间过不去
#include <iostream> #include <cstdlib> #include < string> #include <algorithm> #include <vector> #include <stack> #include <queue> #include <map> #include <sstream> using namespace std; string ato_string( int value){ stringstream ss; ss << value; return ss.str(); } void out (vector< int> v){ for( int i = 0; i < v.size(); i++){ cout<<v[i]<< " "; } cout<<endl; } vector<vector< int> > deep(vector< int> num, int target, int index){ if (index == 0 || num.size() < index) { vector<vector< int> > t; return t; } vector<vector< int> > result; for( int i = 0; i < num.size(); i++){ int tmp = num[i]; if (index == 1) { if (tmp == target) { vector< int> t; t.push_back(tmp); result.push_back(t); } continue; } vector< int> copy = num; copy.erase(copy.begin() + i); vector<vector< int> > re = deep(copy, target - tmp, index- 1); for ( int j = 0; j < re.size(); ++j) { vector< int> t = re[j]; t.push_back(tmp); result.push_back(t); } } for( int i = 0; i < result.size(); i++){ sort(result[i].begin(), result[i].end()); } return result; } vector<vector< int> > fourSum(vector< int> &num, int target) { vector<vector< int> > r = deep(num, target, 4); map< string, bool> m; for( int i = 0 ; i != r.size(); ++i){ string key = ato_string(r[i][ 0]) + ato_string(r[i][ 1]) + ato_string(r[i][ 2]) + ato_string(r[i][ 3]); if(m.find(key) != m.end()){ r.erase(r.begin()+i); i--; } else{ m[key] = true; } } return r; } int main( int argc, char** argv) { vector< int> s; s.push_back(- 9); s.push_back(- 2); s.push_back( 7); s.push_back( 6); s.push_back(- 8); s.push_back( 5); s.push_back( 8); s.push_back( 3); s.push_back(- 10); s.push_back(- 7); s.push_back( 8); s.push_back(- 8); s.push_back( 0); s.push_back( 0); s.push_back( 1); s.push_back(- 8); s.push_back( 7); vector<vector< int> > r = fourSum(s, 4); for( int i = 0; i < r.size(); i++){ out(r[i]); } return 0 ;}