当前位置: 首页> 科技> 名企 > LeetCode216组合总和3

LeetCode216组合总和3

时间:2025/7/11 13:28:08来源:https://blog.csdn.net/Chisato1021/article/details/139423179 浏览次数:2次

题目描述

  找出所有相加之和为 n 的 k 个数的组合,且满足下列条件:只使用数字1到9。每个数字 最多使用一次。返回 所有可能的有效组合的列表 。该列表不能包含相同的组合两次,组合可以以任何顺序返回。

解析

  递归加剪枝,搜索长度达到k就可以返回,另外当选择的数之和比n还大的时候就可以不用再搜索了。

public List<List<Integer>> combinationSum3(int k, int n) {List<List<Integer>> res = new ArrayList<>();boolean[] isChosen = new boolean[10];List<Integer> current = new ArrayList<>();DFS(res, current, isChosen, 0, k, n, 1);return res;}private void DFS(List<List<Integer>> res,List<Integer> current,boolean[] isChosen,int curSum,int k,int n,int start) {if(current.size() == k) {if(curSum == n) {res.add(new ArrayList<>(current));}return;}for(int i = start; i <= 9 ; i++) {if(!isChosen[i]) {current.add(i);curSum += i;if(curSum <= n) {isChosen[i] = true;DFS(res, current, isChosen, curSum, k, n, i + 1);}current.remove(current.size() - 1);curSum -= i;isChosen[i] = false; // 回溯}}}

在这里插入图片描述

关键字:LeetCode216组合总和3

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: