LeetCode 面试题57 - II. 和为s的连续正数序列
输入一个正整数 target ,输出所有和为 target 的连续正整数序列(至少含有两个数)。
序列内的数字由小到大排列,不同序列按照首个数字从小到大排列。
示例 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、暴力
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47#include <iostream> #include <vector> #include <queue> #include <map> #include <stack> #include <math.h> #include <string> using namespace std; class Solution { public: // 暴力 vector<vector<int>> findContinuousSequence(int target) { vector<vector<int>> rst; if (target <= 2) { return rst; } // 数组 vector<int> 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<int> tempNode; tempNode.insert(tempNode.end(), node.begin() + begin, node.begin() + i + 1); rst.push_back(tempNode); } begin++; } return rst; } };
最后
以上就是真实火最近收集整理的关于LeetCode 面试题57 - II. 和为s的连续正数序列的全部内容,更多相关LeetCode内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复