和为S的连续正数序列
和为S的连续正数序列
http://www.nowcoder.com/questionTerminal/c451a3fd84b64cb19485dad758a55ebe
剑指offer原算法Java实现
import java.util.ArrayList; public class Solution { public ArrayList<ArrayList<Integer>> FindContinuousSequence(int sum) { ArrayList<ArrayList<Integer>> resultTotal=new ArrayList<ArrayList<Integer>>(); //边界条件 if(sum<3){ return resultTotal; }else{ int small=1; int big=2; int curSum=big+small; while(small<(1+sum)/2){ if(curSum==sum){ //为了防止覆盖,每次都需要重新new ArrayList<Integer> result=new ArrayList<Integer>(); for(int i=small;i<=big;i++){ result.add(i); } resultTotal.add(result); } while(curSum>sum&&small<(1+sum)/2){ curSum-=small; small++; if(curSum==sum){ //为了防止覆盖,每次都需要重新new ArrayList<Integer> result=new ArrayList<Integer>(); for(int i=small;i<=big;i++){ result.add(i); } resultTotal.add(result); } } big++; curSum+=big; } } return resultTotal; } }