首页 > 代码库 > 216. Combination Sum III
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.
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]]
Credits:
Special thanks to @mithmatt for adding this problem and creating all test cases.
public class Solution { public List<List<Integer>> combinationSum3(int k, int n) { int nums[] = {1,2,3,4,5,6,7,8,9}; List<List<Integer>> res = new ArrayList<>(); List<Integer> member = new ArrayList<>(); dfs(res, member, 0, nums, n, k); return res; } public void dfs(List<List<Integer>> res, List<Integer> member, int deep, int[] nums, int n, int k){ if(member.size() > k || n < 0) return; if(member.size() == k && n == 0) { res.add(new ArrayList<>(member)); return; } for(int i = deep ; i < nums.length; i++){ member.add(nums[i]); dfs(res, member, i+1, nums, n-nums[i], k); member.remove(member.size()-1); } } }
216. Combination Sum III
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。