2021-07-22 合为s的连续正数和

前缀和的思想,两个for循环

public ArrayList> FindContinuousSequence(int sum) {
        ArrayList> res = new ArrayList();
        if(sum == 1 || sum == 0){
            return res;
        }
        int numsLen = (int)(sum/2)+2;
        int[] sums = new int[numsLen];
        sums[0] = 0;
        for(int i =1 ;i < numsLen;i++){
            sums[i] = sums[i-1]+i;
        }
        for(int i =0 ;i < numsLen;i++){
            for(int j= i+1;j < numsLen;j++){
                if(sums[j]-sums[i] == sum){
                    ArrayList temp = new ArrayList();
                    for(int k = i+1;k<=j;k++){
                        temp.add(k);
                    }
                    res.add(temp);
                }
            }
        }
        return res;
    }

你可能感兴趣的:(2021-07-22 合为s的连续正数和)