import java.util.ArrayList;
import java.util.List;
/**
* 给定一个数字x,要求使用k个数字求和可以得到x,数字从1-9中选择,不能重复。
*
* 实现一个函数,在输入 x,k 时,输出所有可以求和得到x的列表
*
* 例子:
*
* 输入:k= 3, x = 9
*
* 输出: [[1,2,6], [1,3,5], [2,3,4]]
*/
public class CombinationSum3 {
public static void main(String[] args){
List<List<Integer>> list = combinationSum(3,9);
for(int i=0;i<list.size();i++){
for (int j=0;j<list.get(i).size();j++){
System.out.print(list.get(i).get(j));
}
System.out.println();
}
}
public static List<List<Integer>> combinationSum(int k, int x){
List<List<Integer>> list = new ArrayList<>();
helper(list,new ArrayList<Integer>(),k,x,1);
return list;
}
private static void helper(List<List<Integer>> list, ArrayList<Integer> tempList,int k, int x, int start) {
if(tempList.size()>k){
return ;
}
if(tempList.size() == k && x == 0){
list.add(new ArrayList<>(tempList));
return ;
}
for(int i=start;i<=9;i++){
tempList.add(i);
helper(list,tempList,k,x-i,i+1);
tempList.remove(tempList.size() -1 );
}
}
}