找出所有相加之和为 n 的 k 个数的组合。组合中只允许含有 1 - 9 的正整数,并且每种组合中不存在重复的数字。
说明:
所有数字都是正整数。
解集不能包含重复的组合。
示例 1:
输入: k = 3, n = 7
输出: [[1,2,4]]
示例 2:
输入: k = 3, n = 9
输出: [[1,2,6], [1,3,5], [2,3,4]]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/combination-sum-iii
思路:
懂了一和二(前面已经做过一和二了这是三,变种),再来再多3456789都不怕
还是一样的用DFS,变了的是给定的数字是1-9的正整数之间呗
不能重复呗,盘他
class Solution {public static List<List<Integer>> combinationSum3(int k, int n) {List<List<Integer>> res = new LinkedList<>();if (n == 0){return res;}Deque<Integer> path = new ArrayDeque<>();dfs(k,n,path,res,1);return res;}private static void dfs(int k, int n, Deque<Integer> path, List<List<Integer>> res,int first) {if (k == 0 && n == 0){res.add(new ArrayList<>(path));return;}if (k == 0 || n == 0) {return;}for (int i = first; i <= 9; i++) {path.add(i);dfs(k - 1 , n - i , path, res,i + 1);path.remove(i);}}}
