组合总和 III (Combination Sum III)

 

思路:

// @Title: 组合总和 III (Combination Sum III)
// @Author: qisiii
// @Date: 2024-09-19 21:32:13
// @Runtime: 0 ms
// @Memory: 40 MB
// @comment: 
// @flag: 
class Solution {
    public List<List<Integer>> combinationSum3(int k, int n) {
        List<List<Integer>> result = new ArrayList<>();
        dfs(result, new ArrayList<>(), 1, 0, k, n);
        return result;
    }

    private void dfs(List<List<Integer>> result, List<Integer> list, int cur, int sum, int k, int n) {
        if (list.size() == k && sum == n) {
            result.add(new ArrayList<>(list));
            return;
        }
        if (list.size() > k || sum > n || cur > 9) {
            return;
        }
        list.add(cur);
        dfs(result, list, cur + 1, sum + cur, k, n);
        list.remove(list.size() - 1);
        dfs(result, list, cur + 1, sum, k, n);
    }

}
Licensed under CC BY-NC-SA 4.0
最后更新于 2024-10-18