题目描述:
输入一个正整数 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
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解答:
/**
* Return an array of arrays of size *returnSize.
* The sizes of the arrays are returned as *returnColumnSizes array.
* Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
*/
int** findContinuousSequence(int target, int* returnSize, int** returnColumnSizes)
{
int** res = (int**)malloc(sizeof(int*)*target);
int* col = (int*)malloc(sizeof(int)*target);
int i = 0;
int j = 0;
int k = 0;
int m = 0;
int index = 0;
int sum = 0;
for(i = 1;i < target;i++) //从第1个数开始,因为至少含两个数,所以i<target
{
for(j = i;sum <= target;j++)//寻找符合的值
{
if(target == sum)
{
col[index] = j - i;
res[index] = (int*)malloc(sizeof(int) * (j - i));
for(k = i; k < j ;k++)
{
res[index][m] = k;
m++;
}
m = 0;
index++;
}
sum += j;
}
sum = 0;
}
*returnSize = index;
*returnColumnSizes = col;
return res;
}
运行结果: