您的位置:首页 > 其它

【Leetcode】Combination Sum III

2015-11-28 16:18 330 查看
题目链接:https://leetcode.com/problems/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.
Ensure that numbers within the set are sorted in ascending order.

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]]


思路:

候选集没有重复元素,每个元素只选一次,跟上题不同的是,限制了搜索步数。因为没有重复解的问题,所以无需用HashSet,只需要加入对步数的判断就好了

算法:

List<List<Integer>> iLists = new ArrayList<List<Integer>>();
List<Integer> list = new ArrayList<Integer>();
int target = 0;
int k = 0;

public List<List<Integer>> combinationSum3(int k, int n) {
this.target = n;
this.k = k;
dspCombination(0, 1);
return iLists;
}

private void dspCombination(int sum, int level) {
if (sum == target && list.size() == k) { //限制搜索步数
iLists.add(new ArrayList<Integer>(list));
return;
} else if (list.size() > k) {
return;
} else if (sum > target) {
return;
} else {
for (int i = level; i <= 9; i++) {
sum += i;
list.add(i);
dspCombination(sum, i + 1);//
list.remove(list.size() - 1);
sum -= i;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: