题目描述
小明很喜欢数学,有一天他在做数学作业时,要求计算出9~16的和,他马上就写出了正确答案是100。但是他并不满足于此,他在想究竟有多少种连续的正数序列的和为100(至少包括两个数)。没多久,他就得到另一组连续正数和为100的序列:18,19,20,21,22。现在把问题交给你,你能不能也很快的找出所有和为S的连续正数序列? Good Luck!
输出描述:
输出所有和为S的连续正数序列。序列内按照从小至大的顺序,序列间按照开始数字从小到大的顺序
思路一
import java.util.ArrayList;
public class Continuous {
public static void main(String[] args){
Continuous continuous = new Continuous();
ArrayList<ArrayList<Integer>> arrayLists = continuous.FindContinuousSequence(9);
for(ArrayList<Integer> sub : arrayLists){
for(int i = 0; i < sub.size(); i++){
System.out.print(sub.get(i));
}
System.out.println(sub.toArray());
}
}
public ArrayList<ArrayList<Integer> > FindContinuousSequence(int sum) {
ArrayList<ArrayList<Integer> > result = new ArrayList<>();
int low = 1,high = 2;
while(high > low){
//由于是连续的,差为1的一个序列,那么求和公式是(a0+an)*n/2
int cur = (high + low) * (high - low + 1) / 2;
if(cur == sum){
ArrayList<Integer> list = new ArrayList<>();
for(int i=low;i<=high;i++){
list.add(i);
}
result.add(list);
high++;
}else if(cur < sum){
high++;
}else{
low++;
}
}
return result;
}
}
思路二
import org.omg.CORBA.PUBLIC_MEMBER;
import javax.swing.text.StyleContext;
import java.util.ArrayList;
public class COtinu {
public static void main(String[] args){
COtinu cOtinu = new COtinu();
ArrayList<ArrayList<Integer>> arrayLists = cOtinu.FindContinuousSequence(9);
for(ArrayList<Integer> sub : arrayLists){
for(int i = 0; i < sub.size(); i++){
System.out.print(sub.get(i));
}
System.out.println(sub.toArray());
}
}
public ArrayList<Integer> addToSubList(int low,int high){
ArrayList<Integer> subList = new ArrayList<>();
for(;low <= high;low++){
subList.add(low);
}
return subList;
}
public ArrayList<ArrayList<Integer>> FindContinuousSequence(int sum) {
ArrayList<ArrayList<Integer>> list = new ArrayList<>();
if(sum == 1){
ArrayList<Integer> subList = new ArrayList<>();
subList.add(1);
list.add(subList);
return list;
}
if(sum == 2) return null;
int low = 1;
int high = 2;
int middle = (sum - 1) / 2;
int curSum = low + high;
while (low < high){
if(curSum == sum){
list.add(addToSubList(low, high));
}
while (curSum > sum && low < middle){
curSum -= low;
low++;
if(curSum == sum){
list.add(addToSubList(low, high));
}
}
high++;
curSum += high;
}
return list;
}
}
该种思路的时间复杂度过大
思路三
public ArrayList<ArrayList<Integer>> FindContinuousSequence(int sum) {
ArrayList<ArrayList<Integer>> ans = new ArrayList<>();
for (int n = (int) Math.sqrt(2 * sum); n >= 2; n--) {
//n分别为奇数或偶数的情况
//n为奇数时需要满足(n & 1) == 1 && sum % n == 0
//n为偶数时需要满足(sum % n) * 2 == n)
if ((n & 1) == 1 && sum % n == 0 || (sum % n) * 2 == n) {
ArrayList<Integer> list = new ArrayList<>();
for (int j = 0, k = (sum / n) - (n - 1) / 2; j < n; j++, k++) {
list.add(k);
}
ans.add(list);
}
}
return ans;
}