题目描述
小明很喜欢数学,有一天他在做数学作业时,要求计算出9~16的和,他马上就写出了正确答案是100。但是他并不满足于此,他在想究竟有多少种连续的正数序列的和为100(至少包括两个数)。没多久,他就得到另一组连续正数和为100的序列:18,19,20,21,22。现在把问题交给你,你能不能也很快的找出所有和为S的连续正数序列? Good Luck!
输出描述:
输出所有和为S的连续正数序列。序列内按照从小至大的顺序,序列间按照开始数字从小到大的顺序
import java.util.ArrayList;
public class Solution {
public ArrayList<ArrayList<Integer> > FindContinuousSequence(int sum) {
ArrayList<ArrayList<Integer> > res=new ArrayList<>();
ArrayList<Integer> al=new ArrayList<>();
int before=0,now=0;
if(sum<=2)return res;
for(int i=1;i<sum;i++){
now+=i;
if(now==sum){
al.add(i);
res.add(new ArrayList<Integer>(al));
break;
}else if(now>sum){
now-=i;
break;
}
al.add(i);
}
for(int i=2;i<sum;i++){
now-=al.get(0);
al.remove(0);
if(al.size()==0)break;//防止数组越界
int add=al.get(al.size()-1)+1;
if(now+add==sum){
now+=add;
al.add(add);
res.add(new ArrayList<Integer>(al));
}else if(now+add<sum){
now+=add;
al.add(add);
}
}
return res;
}
}
改进:
一个循环就可以解决
import java.util.ArrayList;
public class Solution {
public ArrayList<ArrayList<Integer> > FindContinuousSequence(int sum) {
ArrayList<ArrayList<Integer> > res=new ArrayList<>();
ArrayList<Integer> al=new ArrayList<>();
int now=1;
al.add(1);
if(sum<=2)return res;
while(true){
if(al.size()==0)break;//防止数组越界
int add=al.get(al.size()-1)+1;
if(now+add==sum){
now+=add;
al.add(add);
res.add(new ArrayList<Integer>(al));
}else if(now+add<sum){
now+=add;
al.add(add);
continue; //该情况下不能再执行后续代码移除首位元素
}
now-=al.get(0);
al.remove(0);
}
return res;
}
}
继续改进:发现只要连续个数小于2了,意味着已经到达了遍历终点,在此之后两个连续数相加必然大于目标值。
import java.util.ArrayList;
public class Solution {
public ArrayList<ArrayList<Integer> > FindContinuousSequence(int sum) {
ArrayList<ArrayList<Integer> > res=new ArrayList<>();
if(sum<=2)return res;
ArrayList<Integer> al=new ArrayList<>();
al.add(1);
al.add(2);
int count=3,now=3;
while(al.size()>=2){
if(count<sum){
count+=now;
al.add(now++);
continue;
}
if(count==sum){
res.add(new ArrayList<Integer>(al));
}
count-=al.remove(0);
}
return res;
}
}