连续数字的所有可能总和,等于数组中的N.

时间:2016-01-10 06:35:50

标签: java arrays

我试图从数组中连续元素中找到所有可能的总和,这些元素会添加到特定数字。 例如: -

a[] = {4,7,2,1,3,8,5}; and N = 13,
Output = {4,7,2},{7,2,1,3},{8,5} 

这是我的代码 -

 int low = 0;
        int high = 0;
        int sum = a[0];
        while(high < a.length) {
            if(sum < 13) {
                high++;

                if(high < a.length) {
                    sum+= a[high];

                }
            } else if(sum > 13) {
                sum-=a[low];
                low++;

            }
            if(sum == 13) {
                for(int i=low;i<=high;i++) {
                    System.out.println(a[i]);
                }
                System.out.println("new ");
                low++;
                high++;
                sum = 0;
                //return;
            }
        }

但输出只返回一组{4,7,2}。我无法打印其他套装。任何人都可以帮我解决这个问题

2 个答案:

答案 0 :(得分:2)

找到第一个序列后,您没有正确重置变量:

        if(sum == 13) {
            for(int i=low;i<=high;i++) {
                System.out.println(a[i]);
            }
            System.out.println("new ");
            low++;
            high++; // change to high = low; // since you want your loop to test 
                    // sequences that start at the new (post incremented) low
            sum = 0; // change to sum = a[low]; // since the initial sum is the value of
                     // the first element in the new sequence
        }

答案 1 :(得分:0)

如果数组可能包含零或负数。

    int a[] = {4,7,2,1,3,8,5,-1,1};
    int length = a.length;
    for (int low = 0; low < length; ++low) {
        int sum = a[low];
        for (int high = low + 1; high < length; ++high) {
            sum += a[high];
            if (sum == 13) {
                for (int k = low; k <= high; ++k)
                    System.out.print(a[k] + " ");
                System.out.println();
            }
        }
    }

结果:

4 7 2 
7 2 1 3 
8 5 
8 5 -1 1