LeetCode面接問題57-II.とsの連続正数シーケンス

1674 ワード

LeetCode面接問題57-II.とsの連続正数シーケンス
正の整数targetを入力し、targetとなるすべての連続正の整数シーケンス(少なくとも2つの数を含む)を出力します.
シーケンス内の数字は小さいから大きいまで並べられ、異なるシーケンスは最初の数字に従って小さいから大きいまで並べられます.
例1:
入力:target=9出力:[[2,3,4],[4,5]]
例2:
入力:target=15出力:[[1,2,3,4,5],[4,5,6],[7,8]]
制限:
1 <= target <= 10^5
ソース:力ボタン(LeetCode)リンク:https://leetcode-cn.com/problems/he-wei-sde-lian-xu-zheng-shu-xu-lie-lcof/著作権はインターネットの所有に帰属する.商業転載は公式の授権に連絡してください.非商業転載は出典を明記してください.
1、暴力
#include 
#include 
#include 
#include 
#include 
#include 
#include 

using namespace std;

class Solution {
public:
    //   
    vector> findContinuousSequence(int target) {
        vector> rst;
        if (target <= 2) {
            return rst;
        }

        //   
        vector node(target + 1);
        for (size_t i = 0; i < target + 1; i++) {
            node[i] = i;
        }

        int begin = 1;
        while (begin <= target / 2) {   //            
            int total = begin;
            int i = begin + 1;
            while (i < target) {
                total += i;
                if (total >= target) {
                    break;
                }
                i++;
            }
            if (target == total) {
                vector tempNode;
                tempNode.insert(tempNode.end(), node.begin() + begin, node.begin() + i + 1);
                rst.push_back(tempNode);
            }
            begin++;
        }

        return rst;
    }
};