Question
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.
找出K个数字总和为n的所有可能情况,给出的K个数字的大小在1-9之间,每个数字在一种情况中只能使用一次
Exameple
Input: k = 3, n = 7
Output: [[1,2,4]]
Input: k = 3, n = 9
Output: [[1,2,6], [1,3,5], [2,3,4]]
Solution
回溯解。因为要列出所有情况,所以我们只要遍历所有可能性并且取出K个元素总和为n的情况即可。
public class Solution { public List<List<Integer>> combinationSum3(int k, int n) { List<List<Integer>> res = new ArrayList<>(); backtracking(1, k, n, res, new ArrayList<>()); return res; } /** * 思路:遍历所有可能性并且取出K个元素总和为n的情况 * @param start: 当前加入链表的元素索引 * @param k:需要K个数 * @param n:还需要达到的目标值 * @param res:保存所有结果 * @param temp:保存当前组合的链表 */ public void backtracking(int start, int k, int n, List<List<Integer>> res, List<Integer> temp){ // 如果当前链表中的元素大于K个,直接返回 if(k < temp.size()) return; // 如果K个元素的总和等于n,则添加到结果集并返回 if(k == temp.size() && n == 0){ // 拷贝一个链表,因为temp接下去还会被修改 List<Integer> newTempList = new ArrayList<>(temp); res.add(newTempList); return; } // 回溯 for(int i = start; i < 10; i++){ temp.add(i); backtracking(i + 1, k,n - i, res, temp); // 每次使用后都清空使用过的元素 temp.remove(temp.size() - 1); } } }