其他分享
首页 > 其他分享> > 剑指offer-面试题57_2-和为s的连续正数序列-穷举法

剑指offer-面试题57_2-和为s的连续正数序列-穷举法

作者:互联网

/*
题目:
	输入一个整数s,输出所有和为s的连续整数序列。
*/
/*
思路:
	穷举法。
*/
#include<iostream>
#include<cstring>
#include<vector>
#include<algorithm>
#include<map>

using namespace std;

vector<vector<int> > FindContinuousSequence(int sum) {
    vector<vector<int> > res;
    int half = sum / 2;
    int ceil_half = (sum+1) / 2;

    for(int i = 1; i <= half; i++){
        int curr = i;
        for(int j = i + 1; j <= ceil_half; j++){
            curr += j;
            if(curr == sum){
                vector<int> sequence;
                for(int index = i; index <= j; index++){
                    sequence.push_back(index);
                }
                res.push_back(sequence);
                i++;
                break;
            }
            else if(curr > sum){
                break;
            }
        }
    }
    return res;
}
int main(){
    vector<vector<int> > res = FindContinuousSequence(15);
    for(int i = 0; i < res.size(); i++){
        for(int j = 0; j < res[i].size(); j++){
            cout<<res[i][j]<<" ";
        }
        cout<<endl;
    }
}

   

标签:面试题,offer,int,res,sum,穷举法,vector,include
来源: https://www.cnblogs.com/buaaZhhx/p/12108682.html