Title Description
Xiao Ming is very fond of mathematics, one day when he was doing math homework, required to calculate and 9 to 16, he immediately wrote the correct answer is 100. But he was not satisfied with this, he wondered how many kinds of continuous positive number sequence is 100 (including at least two numbers). Before long, he got another set of consecutive positive number and a sequence of 100: 18,19,20,21,22. Now the question to you, you can also quickly identify all positive and continuous sequence S? Good Luck!
Output Description :
输出所有和为S的连续正数序列。序列内按照从小至大的顺序,序列间按照开始数字从小到大的顺序
This question can use the idea of dynamic programming algorithm we initialize an array, the array is smaller than sum
the positive number of unique sort the array, we create two pointers left
to the right
point of 0, and then create a new variable count
record from left
a pointer to right
and an array of pointers. Then start while
cycles each comparison count
with sum
the size, if count
smaller, then so right++
; if count
large, will make it left--
, then it will equal left
a pointer to right
an array of pointers into the res
middle. End of the cycle return res
to.
function FindContinuousSequence(sum)
{
let i = 1;
let temp = new Array(sum-1).fill(1).map(x=>i++)
let res = [];
let left = 0;
let right = 0;
let count = 0;
while(right!=sum){
if(count<sum){
count += temp[right];
right++;
}
else if(count==sum){
res.push(temp.slice(left, right));
count -= temp[left];
left++;
}else{
count -= temp[left];
left++;
}
}
return res;
}