代码编程

此博客链接:https://www.cnblogs.com/ping2yingshi/p/12427776.html。

和为s的连续正数序列

题目链接:https://leetcode-cn.com/problems/he-wei-sde-lian-xu-zheng-shu-xu-lie-lcof/description/

输入一个正整数 target ,输出所有和为 target 的连续正整数序列(至少含有两个数)。

序列内的数字由小到大排列,不同序列按照首个数字从小到大排列。

示例 1:

输入:target = 9

输出:[[2,3,4],[4,5]]

示例 2:

输入:target = 15

输出:[[1,2,3,4,5],[4,5,6],[7,8]]

题解:这道题一开始想用等差数列做,但是由于不会存储数据,就选择了另外一种方法,找规律的方法。

思想:以 9为例子,9可以被拆开成 4+5。

如果是 [4,5] 的话,i=2,(target-1) % 2 = 0 其中 [4,5]可以改写成 4+(4+1)。

在考虑三个元素的时候 2+3+4 我们发现他可以被写成 2+(2+1)+(2+2), i = 3, (target-3)%3 = 0。

开始元素 *元素个数,如果 target 刚好为这个值的话,也能满足 target%i=0,target/i 就是我们需要的值.

代码如下

class Solution {
    public int[][] findContinuousSequence(int target) {
        
        List<int[]> result = new ArrayList<>();
        int i = 1;

        while(target>0)
        {
            target -= i++;
            if(target>0 && target%i == 0)
            {
                int[] array = new int[i];
                for(int k = target/i, j = 0; k < target/i+i; k++,j++)
                {
                    array[j] = k;
                }
                result.add(array);
            }
        }
        Collections.reverse(result);
        return result.toArray(new int[0][]);       
    }
}
原文地址:https://www.cnblogs.com/ping2yingshi/p/12427776.html