您的位置:首页 > 其它

[LeetCode]216. Combination Sum III

2016-12-12 16:50 176 查看
https://leetcode.com/problems/combination-sum-iii/

回溯,注意要记录前一个位置,避免出现[1,2,3]和[2,1,3]同时出现的错误。

public class Solution {
List<List<Integer>> res;
public List<List<Integer>> combinationSum3(int k, int n) {
res = new LinkedList<>();
if (k > 9 || n < 1 || n > 45) {
return res;
}
combinationSum3(k, n, new LinkedList<Integer>(), 0);
return res;
}
private void combinationSum3(int k, int n, LinkedList<Integer> temp, int pos) {
if (k == 0 && n == 0) {
res.add(new LinkedList<Integer>(temp));
return;
} else if (k == 0 || n == 0) {
return;
}
for (int i = pos + 1; i <= 9; i++) {
temp.add(i);
combinationSum3(k - 1, n - i, temp, i);
temp.removeLast();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: