0216.组合总和III
描述
找出所有相加之和为 *n *的 **k 个数的组合。**组合中只允许含有 1 - 9 的正整数,并且每种组合中不存在重复的数字。
说明
- 所有数字都是正整数。
- 解集不能包含重复的组合。
实例
输入: k = 3, n = 7
输出: [[1,2,4]]
输入: k = 3, n = 9
输出: [[1,2,6], [1,3,5], [2,3,4]]
题解
- 深度搜索
- 在
for
循环里由小到大的把所有可能值放在state[index]
里 k==index
时检测sum
是否合法,合法则保存if (k-index-1 > 9-nowNum)
检测后续的位置是否足够存放到9
- 可以做但是未实现的优化
- 计算当前情况下,填入后续数字最大若仍小于
n
则停止尝试 - 计算当前情况下,填入后续数字最小若仍大于
n
则停止尝试
- 计算当前情况下,填入后续数字最大若仍小于
public static List<List<Integer>> combinationSum3(int k, int n) {
List<List<Integer>> res = new LinkedList<>();
int[] state = new int[k];
getAllCombina4_216(k,n,1,0,0,state,res);
return res;
}
public static void getAllCombina4_216(int k,int n,int nowNum,int index ,int sum,int[] state,List<List<Integer>> res){
if (index == k){
if (sum != n)
return;
List<Integer> nowList = new ArrayList<>();
for (Integer i:state)
nowList.add(i);
res.add(nowList);
return;
}
if (sum > n)
return;
if (k-index-1 > 9-nowNum)
return;
for (int i=nowNum;i <= Math.min(9,n-sum);i++){
state[index] = i;
getAllCombina4_216(k,n,i+1,index+1,sum+i,state,res);
}
}