题目描述
小明很喜欢数学,有一天他在做数学作业时,要求计算出9~16的和,他马上就写出了正确答案是100。但是他并不满足于此,他在想究竟有多少种连续的正数序列的和为100(至少包括两个数)。没多久,他就得到另一组连续正数和为100的序列:18,19,20,21,22。现在把问题交给你,你能不能也很快的找出所有和为S的连续正数序列? Good Luck!
输出描述:
输出所有和为S的连续正数序列。序列内按照从小至大的顺序,序列间按照开始数字从小到大的顺序
算法:
考虑两个数字small和big分别表示序列的最小值与最大值。首先令small=1,big=2,动态维护区间[small,big]及当前区间的数字和curSum,利用连续序列和的特性,只要small==(sum+1)/2就可以提前结束。
class Solution {
public:
vector<vector<int> > FindContinuousSequence(int sum) {
vector<vector<int>> res;
if(sum<3) return res;
int small=1;
int big=2;
int mid=(sum+1)/2;
int curSum=small+big;
while(small<mid){
if(curSum==sum){
putNumbersIntoRes(small,big,res);
curSum-=small;
small++;
big++;
curSum+=big;
}else if(curSum<sum){
big++;
curSum+=big;
}else{ //curSum>sum
curSum-=small;
small++;
}
}
return res;
}
private:
void putNumbersIntoRes(const int& small,const int& big,vector<vector<int>>& res){
vector<int> vec;
for(int i=small;i<=big;i++){
vec.push_back(i);
}
res.push_back(vec);
}
};
class Solution {
public:
vector<vector<int>> FindContinuousSequence(int sum) {
if (sum < 3) {
return {};
}
// [left, right]
int left = 1, right = 2, limit = (sum + 1) >> 1, curSum = left + right;
vector<vector<int>> res;
while (left < limit) {
if (curSum == sum) {
printNumberToRes(left, right, res);
curSum -= left;
++left;
++right;
curSum += right;
} else if (curSum < sum) {
++right;
curSum += right;
} else {
curSum -= left;
++left;
}
}
return res;
}
private:
void printNumberToRes(int left, int right, vector<vector<int>>& res) {
vector<int> ans;
for (int i = left; i <= right; ++i) {
ans.push_back(i);
}
res.push_back(ans);
}
};