Combination Sum III

LeetCode Q 216 - Combination Sum III

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.

Note:

  • All numbers will be positive integers.
  • The solution set must not contain duplicate combinations.

Example 1:
Input: k = 3, n = 7 ; Output: [[1,2,4]]
Example 2:
Input: k = 3, n = 9 ; Output: [[1,2,6], [1,3,5], [2,3,4]]

Solution : Backtracking

Code:

private List<List<Integer>> res;
public List<List<Integer>> combinationSum3(int k, int target) {
	res = new ArrayList<>();
	if (target == 0 || k == 0) return res;
	backtrack(k, target, 1, new ArrayList<>());
	return res;
}

private void backtrack(int k, int target, int pos, List<Integer> temp) {
	if (temp.size() == k && target == 0) {
		res.add(new ArrayList(temp)); return;
	}
	if (temp.size() == k || target <= 0) return;

	for (int i = pos; i <= 9; i++) {
		if (!temp.contains(i)) {
			temp.add(i);
			backtrack(n, target - i, i + 1, temp);
			temp.remove(temp.size() - 1);
		}
	}
}

   Reprint policy


《Combination Sum III》 by Tong Shi is licensed under a Creative Commons Attribution 4.0 International License
  TOC