版权声明: https://blog.csdn.net/weixin_40550726/article/details/82957907
找出所有相加之和为 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]]
思路:回溯算法。
class Solution {
public List<List<Integer>> combinationSum3(int k, int n) {
List<List<Integer>> res=new LinkedList<List<Integer>>();//存储结果集
List<Integer> tmp=new LinkedList<Integer>(); //临时存储找到的数
boolean[] used=new boolean[9]; //用来判断该数是否已经使用过
int nums[]={1,2,3,4,5,6,7,8,9};
combination(res,tmp,used,nums,k,n,0,0);
return res;
}
/**
*
* @param res 结果集
* @param tmp 临时存储遍历到的数
* @param used 用来判断该数是否已经使用
* @param nums 0~9
* @param k 个数
* @param n 目标值和
* @param sum tmp链表中的数的和
* @param index 索引位置
*/
public void combination(List<List<Integer>> res, List<Integer> tmp,boolean[] used,int[] nums,int k,int n,int sum,int index){
if(tmp.size()==k){
if(sum==n){
res.add(new LinkedList<Integer>(tmp));
}
return ;
}
for(int i=index;i<nums.length;i++){
if(used[i]==false){
tmp.add(nums[i]);
sum+=nums[i];
used[i]=true;
}
combination(res,tmp,used,nums,k,n,sum,i+1);
used[tmp.get(tmp.size()-1)-1]=false;
sum-=tmp.get(tmp.size()-1);
tmp.remove(tmp.size()-1);
}
}
}