import java.util.*;
public class Main
{
public static void main(String[] args) throws Exception
{
//必须是有序的列表
List<Integer> list = Arrays.asList(new Integer[]{1,2,3,4,5,6,7,8,9,10,11,12,13,14});
for(int number = 1; number < 5; ++number){
System.out.println(number+"个数 : ");
List<List<Integer>> results = fetchFromSet(list,number,22);
System.out.println("\t"+results);
}
}
static List<List<Integer>> fetchFromSet(List<Integer> list,int number,int summary){
List<List<Integer>> results = new ArrayList<>();
int len =list.size();
if(number == 1){
for(int i = len -1; i > 0; --i){
int current = list.get(i);
if(current < summary)
break;
if(current == summary){
List<Integer> choice = new ArrayList<>();
choice.add(current);
results.add(choice);
}
}
return results;
}
/*
比如从[1,2,3,5,7,10]中选4个,那么最后四个最大,
所以先判断最后四个的和是不是大于等于要求的数
如果不符合,也就不用往下比较了
如果符合,就先取出最后一个数,然后从[1,2,3,5,7]中取三个数
*/
//直接截掉大于summary的部分
List<Integer> temp = new ArrayList<>( new TreeSet<>( list ).headSet(summary+1));
len = temp.size();
while(len>number && sum(temp.subList(len-number,len))>= summary ){
int lastElement = temp.get(len-1);
//因为大于summary/2的数最多一个,所以从ts.headSet(summary/2+1)中选数
TreeSet<Integer> ts = new TreeSet<>(temp);
List<Integer> exceptLast = new ArrayList<>(ts.headSet(summary/2+1));
for(List<Integer> tempList : fetchFromSet(exceptLast,number-1,summary-lastElement)){
tempList.add(lastElement);
results.add(tempList);
}
temp = temp.subList(0,len-1);
len--;
}
return results;
}
static int sum(List<Integer> s){
int sum = 0;
for(Integer i: s){
sum+= i;
}
return sum;
}
}