216. Combination Sum III

题目

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.
Input: k = 3, n = 7
Output:  [[1,2,4]]

分析

这道题和之前的Combination Sum I II类似,都可以用回溯解法。回溯解法的套路是:

check and judge
for each candidate:
    add(candidate);
    recursive();
    remove(candidate);

check and judge : 判定解不合法或者已经达到要求,一个都不能少
for循环里的回溯,每次添加一种可能,下一层后一定要删掉这次添加造成的影响
本体每次只需要从上次添加的数+1开始,因为比这个数小的数添加进集合的所有可能性已经在前面考虑过了。

代码

public void findCombination(int k, int target, int last, List list, List> res){
    if(k == 0 && target == 0){
        res.add(new ArrayList(list));
        return;
    }
    if(k == 0 || target < 0) return;
    
    for(int i = last + 1; i <= 9; ++i){
        list.add(i);
        findCombination(k-1, target-i, i, list, res);
        list.remove(list.size() - 1);
    }
}


public List> combinationSum3(int k, int n) {
    List> res = new ArrayList<>();
    if(k <= 0 || n <= 0) return res;
    List list = new ArrayList<>();
    findCombination(k, n, 0, list, res);
    return res;
}

你可能感兴趣的:(216. Combination Sum III)