[英]All possible sums of consecutive number that equal to N in an array
我試圖從一個數組中的連續元素中找到所有可能的總和,這些總和加起來等於一個特定的數字。 例如: -
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}
。 我無法打印其他電視機。 誰能幫我解決這個問題
找到第一個序列后,您沒有正確重置變量:
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
}
如果數組可以包含零或負數。
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.