剑指offer,双指针法,vector输出不完美
原因:由于在第一个res push_back给allRes的时候allRes的列已经确定,所以在输出的时候会输出一些多余的东西,在输出的时候不好处理
#include <iostream> #include "algorithm" #include "cmath" #include "string" #include <vector> using namespace std; int main() { int sum=200; vector<vector<int> > allRes; int phigh = 2,plow = 1; while(phigh > plow){ int cur = (phigh + plow) * (phigh - plow + 1) / 2; if( cur < sum) phigh++; if(cur == sum){ vector<int> res; for(int i = plow; i<=phigh; i++) res.push_back(i); allRes.push_back(res); plow++; //vector<int>().swap(res); res.clear(); } if(cur > sum) plow++; } // for( vector<vector<int> >::iterator it=allRes.begin();it!=allRes.end();it++){error cout // cout<<*it<<endl; // } for(int i=0;i<allRes.size();i++){//right cout for(int j=0;j<allRes[0].size();j++){ cout<<allRes[i][j]<<" "; }cout<<'\n'; } }
直接用二维数组进行替代,输出更好控制
#include <iostream> #include "algorithm" #include "cmath" #include "string" #include <vector> using namespace std; int main() { int sum=200; int allRes[100][100]={0}; int phigh = 2,plow = 1; int t=0; while(phigh > plow){ int cur = (phigh + plow) * (phigh - plow + 1) / 2; if( cur < sum) phigh++; if(cur == sum){ for(int j=plow;j<=phigh;j++){ allRes[t][j-plow]=j; }t++; plow++; //vector<int>().swap(res); //res.clear(); } if(cur > sum) plow++; } // for( vector<vector<int> >::iterator it=allRes.begin();it!=allRes.end();it++){error cout // cout<<*it<<endl; // } int f=1; for(int i=0;i<100;i++){//right cout if(f==0) break; for(int j=0;j<100;j++){ if(allRes[i][0]==0){ f=0;break; } if(allRes[i][j]) cout<<allRes[i][j]<<" "; }cout<<'\n'; } }
不一样的烟火