?LeetCode刷題實(shí)戰(zhàn)216:組合總和 III
Find all valid combinations of k numbers that sum up to n such that the following conditions are true:
Only numbers 1 through 9 are used.
Each number is used at most once.
Return a list of all possible valid combinations. The list must not contain the same combination twice, and the combinations may be returned in any order.
題意
所有數(shù)字都是正整數(shù)。
解集不能包含重復(fù)的組合。
示例
示例 1:
輸入: k = 3, n = 7
輸出: [[1,2,4]]
示例 2:
輸入: k = 3, n = 9
輸出: [[1,2,6], [1,3,5], [2,3,4]]
解題
class Solution {
private static List<List<Integer>> list;
private static List<Integer> tem;
public List<List<Integer>> combinationSum3(int k, int n) {
list = new ArrayList<List<Integer>>();
tem = new ArrayList<>();
dfs(k,n,0,0,1);
return list;
}
public void dfs(int k, int n,int sum,int cnt,int start) {
for (int i = start; i < 10; i++) {
if(sum+i > n || tem.size() > k) {
return;
}
tem.add(i);
if(sum+i == n && tem.size() == k) {
List<Integer> tem0 = new ArrayList<>();
tem0.addAll(tem);
list.add(tem0);
tem.remove(tem.size()-1);
return;
}
dfs(k,n,sum+i,cnt+1,i+1);
if(tem.size() > 0) {
tem.remove(tem.size()-1);
}
}
}
}
LeetCode1-200題匯總,希望對你有點(diǎn)幫助!
LeetCode刷題實(shí)戰(zhàn)201:數(shù)字范圍按位與
LeetCode刷題實(shí)戰(zhàn)202:快樂數(shù)
LeetCode刷題實(shí)戰(zhàn)203:移除鏈表元素
LeetCode刷題實(shí)戰(zhàn)204:計數(shù)質(zhì)數(shù)
LeetCode刷題實(shí)戰(zhàn)205:同構(gòu)字符串
LeetCode刷題實(shí)戰(zhàn)206:反轉(zhuǎn)鏈表
LeetCode刷題實(shí)戰(zhàn)207:課程表
LeetCode刷題實(shí)戰(zhàn)208:實(shí)現(xiàn) Trie (前綴樹)
LeetCode刷題實(shí)戰(zhàn)209:長度最小的子數(shù)組
LeetCode刷題實(shí)戰(zhàn)210:課程表 II
LeetCode刷題實(shí)戰(zhàn)211:添加與搜索單詞
LeetCode刷題實(shí)戰(zhàn)212:單詞搜索 II
LeetCode刷題實(shí)戰(zhàn)213:打家劫舍 II
LeetCode刷題實(shí)戰(zhàn)214:最短回文串
LeetCode刷題實(shí)戰(zhàn)215:數(shù)組中的第K個最大元素
