这道题和Combination Sum II基本相同,不多说了,代码如下
List<List<Integer>> ls = new ArrayList<List<Integer>>();
List<Integer> temp = new ArrayList<Integer>();
int size;
int target;
public List<List<Integer>> combinationSum3(int k, int n) {
if(n < 1){
return ls;
}
size = k;
target = n;
wideSearch(1);
return ls;
}
//熟悉这种回溯方法(dfs)
public void wideSearch(int begin){
//计算当前的temp中的和
int sum = 0;
for(int i = 0;i < temp.size();i ++){
sum += temp.get(i);
}
if(temp.size() == size && sum == target){
ArrayList<Integer> newlist = new ArrayList<Integer>(temp);
ls.add(newlist);
}
else if(sum > target){
return;
}
else{
for(int i = begin;i < 10;i ++){
if(i > target){
return;
}
else{
if(temp.size() < size){
temp.add(i);
wideSearch(i + 1);
temp.remove(temp.size() - 1);
}
}
}
}
}
本文介绍了一种基于回溯法的组合求和算法实现。该算法用于找出所有可能的组合,使得这些组合中的数字之和等于给定的目标值。代码示例展示了如何使用递归进行搜索,并通过剪枝优化来提高效率。
210

被折叠的 条评论
为什么被折叠?



