[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();
}
}
}
回溯,注意要记录前一个位置,避免出现[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();
}
}
}
相关文章推荐
- LeetCode 216. Combination Sum III (组合的和之三)
- leetcode:216. Combination Sum III
- LeetCode 39.Combination Sum,40. Combination Sum II,216. Combination Sum III
- [LeetCode]problem 216. Combination Sum III
- 【leetcode】Minimum Depth of Binary Tree
- [LeetCode] LRU Cache, Solution
- [leetcode]Triangle
- [leetcode] Gray Code
- LeetCode:Construct Binary Tree from Preorder and Inorder Traversal
- leetcode Binary Tree Level Order Traversal
- Leetcode -- Length of Last Word
- [leetCode] Recover Binary Search Tree
- LeetCode Word Search II
- [LeetCode]Letter Combinations of a Phone Number
- Leetcode: Construct Binary Tree from Preorder and Inorder Traversal
- Leetcode || Add Two Numbers
- LeetCode(225) Implement Stack using Queues
- [Leetcode]152. Maximum Product Subarray @python
- 1. Two Sum----LeetCode
- LeetCode 272. Closest Binary Search Tree Value II