DFS_216. 組合總和 III
阿新 • • 發佈:2020-07-24
找出所有相加之和為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); } } }