216. Combination Sum III**

来源:互联网 发布:无人机数据算法 编辑:程序博客网 时间:2024/04/29 15:46

Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers.


Example 1:

Input: k = 3, n = 7

Output:

[[1,2,4]]


Example 2:

Input: k = 3, n = 9

Output:

[[1,2,6], [1,3,5], [2,3,4]]
My code:

public class Solution {    public List<List<Integer>> combinationSum3(int k, int n) {        List<List<Integer>> list = new ArrayList<List<Integer>>();        backtrack(list, new ArrayList<Integer>(), k, 1, n);        return list;    }    private void backtrack(List<List<Integer>> list, List<Integer> tempList, int num, int start,  int remain){        if(remain==0&&num==0) list.add(new ArrayList(tempList));        if(start>remain||num<0) return;        for(int i=start;i<=9;i++){            tempList.add(i);            backtrack(list,tempList,num-1,i+1,remain-i);            tempList.remove(tempList.size()-1);        }    }}
总结:你太棒了,看来还是已经掌握了这种题目的思路。你好棒。




0 0
原创粉丝点击