Java基於遞歸的版本: 代碼裏有簡略的註釋
import java.util.*;
public class Demo {
static ArrayList<ArrayList<Integer>> lists = new ArrayList<>();
static LinkedList<Integer> fuck = new LinkedList<>();
public static void main(String[] args) {
int arr[] = new int[100];
for(int i=0;i<100;i++){
arr[i] = i+1;
}
//100是查找和爲100的數字,0是數組開始位置,arr.length-1是數組結束位置
findList(100,arr,0,arr.length-1);
for(ArrayList list :lists){
System.out.println(list);
}
}
//sun要找的和爲定值的數,arr數組是找數的範圍,start是標記當前遞歸的下標,end是用來跟start判斷的如果小於start就結束遞歸
public static void findList(int sum, int[] arr, int start, int end) {
if (start >= end) {
return;
}
if (sum == arr[start]) {
ArrayList<Integer> list = new ArrayList<>();
for(Integer num :fuck){
list.add(num);
}
list.add(arr[start]);
lists.add(list);
} else {
if (sum > arr[start]) {
fuck.add(arr[start]);
findList(sum - arr[start], arr, start + 1, end);
fuck.remove(fuck.size()-1);
}
findList(sum, arr, start + 1, end);
}
}
}