Combination Sum III

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.

Ensure that numbers within the set are sorted in ascending order.

思路:

  dfs+回溯

我的代码:

public class Solution {
    public List<List<Integer>> combinationSum3(int k, int n) {
        if(k <=0 || n<=0 || k>n) return rst;
        List<Integer> list = new ArrayList<Integer>();
        helper(0, k, n, 1, list);
        return rst;
    }
    public List<List<Integer>> rst = new ArrayList<List<Integer>>();
    public void helper(int sum,int k,int target, int start, List<Integer> list)
    {
        if(sum > target)    return;
        if(k == 0)
        {
            if(sum == target)
                rst.add(new ArrayList(list));
            return;
        }
        for(int i=start; i<=9; i++)
        {
            list.add(i);
            helper(sum+i, k-1, target, i+1, list);
            list.remove(list.size()-1);
        }
    }
}
View Code
原文地址:https://www.cnblogs.com/sunshisonghit/p/4533787.html