[英]All numbers resulting from adding elements of an array
我正在嘗試制作一個給定整數數組的程序,該程序返回所有添加矢量元素后得到的值。
例如:對於數組A = {2,1,3},輸出應為{2,3,5,1,3,4,3,5,4,6}
我需要使用蠻力進行迭代編程,我嘗試使用多個嵌套的for循環來解決它,但是我沒有成功
我會推薦一個遞歸的解決方案
List<Integer> combos(int[] input)
{
return combos(input, 0);
}
List<Integer> combos(int[] input, int offset)
{
if(offset >= input.length) //base case, return 0 for no elements added
{
List<Integer> out = new ArrayList<Integer>((int)Math.pow(2, input.length));
out.add(0);
return out;
}
List<Integer> prev = combos(input, offset + 1);
prev.addAll(prev); //double the previous result
//add input[offset] to half the elements
for(int i = 0; i < prev.size() / 2; i++)
prev.set(i, prev.get(i) + input[offset]);
return prev;
}
輸入{1, 2, 4}
輸出{7, 3, 5, 1, 6, 2, 4, 0}
7,3,5,1,6,2,4,0 {7, 3, 5, 1, 6, 2, 4, 0}
請注意,這包括0
,從技術上講,這兩個元素都不相加
顯然,由於輸出大小將為2^n
,其中n
是輸入向量中的元素數,因此這將很快耗盡內存。
也就是說,您正在尋找向量中所有元素組合的總和。 因此,您要做的就是找到所有組合。 一種簡單的方法是從0 to 2^n
迭代0 to 2^n
並且在每次迭代中僅從向量中選擇索引,在該索引中為其打開了迭代計數器中的位。
這是蠻力方法
package com.test;
import java.util.Arrays;
public class TestCombo {
public static void main(String[] args) {
int[] arr = {2, 1, 3};
int resultCount = (int)Math.pow(2, arr.length);
int[] result = new int[resultCount - 1];
for(int i = 1; i < result.length + 1; i++) {
int j = i;
int sum = 0;
for(int arrI = 0; j != 0; arrI++) {
if( (j & 1) == 1) { //Is arrI bit turned on?
sum += arr[arrI];
}
j = j >> 1;
}
result[i-1] = sum;
}
Arrays.stream(result).forEach(System.out::println);;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.