您可以使用遞歸是的,你可以打破陣列成子部分(我用的List
)。
- 從父親列表的第0指數和空白列表
- 迭代開始了從
i+1
SUBLIST你的父母到底,從而增加從0 to i
- 檢查的
sum
您的工作表(計算)等於你的目標
代碼:
static Integer[] array = { 1, 2, 2, 6, 8, 14, 15, 28, 30, 32, 12, 48, 6, 42 };
static int objective = 50;
public static void main(String args[]) {
add(new ArrayList<Integer>(Arrays.asList(array)),
new ArrayList<Integer>());
}
public static void add(List<Integer> digits, List<Integer> workingList) {
for (int i = 0; i < digits.size(); i++) {
// New sublist to store values from 0 to i
List<Integer> list = new ArrayList<Integer>(workingList);
list.add(digits.get(i));
// Here you call this recursively with your Parent list from i+1
// index and working list from 0 to i
add(digits.subList(i + 1, digits.size()), list);
}
int sum = 0;
for (int element : workingList) {
sum += element;
}
if (sum == objective) {
System.out.println(objective + " = "
+ Arrays.toString(workingList.toArray()));
}
}
輸出:
50 = [1, 2, 2, 15, 30]
50 = [1, 2, 6, 8, 15, 12, 6]
50 = [1, 2, 6, 14, 15, 12]
50 = [1, 2, 14, 15, 12, 6]
50 = [1, 2, 15, 32]
50 = [1, 2, 6, 8, 15, 12, 6]
...
您應該縮小問題的範圍爲一種語言。 – assylias
感謝您的提示,我將編輯問題只是因爲這是我使用了最多的問題 – spuder
http://en.wikipedia.org/wiki/Subset_sum_problem – assylias