216. Combination Sum III

来源:互联网 发布:高中数学知乎 编辑:程序博客网 时间:2024/06/05 06:24

不用多想,直接使用DFS解决

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]]

java

class Solution {    public List<List<Integer>> combinationSum3(int k, int n) {        List<List<Integer>> result = new ArrayList<>();        if (k > n) {            return result;        }        int[] nums = new int[9];        for (int i = 0; i < 9; i++) {            nums[i] = i + 1;        }        dfs(nums, 0, n, k, new ArrayList<Integer>(), result);        return result;    }    private void dfs(int[] nums, int start, int retarget, int limit, List<Integer> path, List<List<Integer>> result) {        if (retarget < 0 || path.size() > limit) {            return;        }        if (retarget == 0 && path.size() == limit) {            result.add(new ArrayList<Integer>(path));            return;        }        for (int i = start; i < nums.length; i++) {            path.add(nums[i]);            dfs(nums, i + 1, retarget - nums[i], limit, path, result);            path.remove(path.size() - 1);        }    }}


原创粉丝点击