216. Combination Sum III

网友投稿 702 2022-09-04

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

class Solution { public List> combinationSum3(int k, int n) { List> res = new ArrayList>(); if(k<1 || n<1) return res; List cur = new ArrayList(); rec(res, cur, 0, k, n, 1); return res; } private void rec(List> res, List cur, int sum, int k, int n, int level) { if(sum==n && k==0) { res.add(new ArrayList(cur)); return; } else if(sum>n || k<=0) return; for(int i=level; i<=9; i++) { cur.add(i); rec(res, cur, sum+i, k-1, n, i+1); cur.remove(cur.size() - 1); } } }

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:数据库索引是什么?新华字典来帮你!(数据库里的索引是什么意思)
下一篇:222. Count Complete Tree Nodes
相关文章

 发表评论

暂时没有评论,来抢沙发吧~