[LeetCode]problem 216. Combination Sum III
2016-06-08 08:46
141 查看
TAG
递归回溯
组合数和
link
方法
与Combination Sum1和Combination Sum2相比,就是上述两个问题的综合,再稍有限制:候选集是
set(1-9)
每个数字只能用一次(组合中各数字是unique)
限制: 必须是k个数。
想想,还是很简单的。加上必要的判断和剪枝即可。
代码
class Solution { public: vector<vector<int>> combinationSum3(int k, int n) { vector<vector<int>> result ; vector<int> selectedNums; selectNum(k, selectedNums, n, result); return result; } private: void selectNum(int k, vector<int> ¤tSelectedNums, int target, vector<vector<int>> &result, size_t startPos=1) { if(currentSelectedNums.size() > k){ return ;} if(target < 0) { return ;} else if(target == 0) { if(currentSelectedNums.size() == k) {result.push_back(currentSelectedNums);} return; } for(int i = startPos; i <= 9 && i <= target; ++i) { // try to add current number to currentSelectedNums currentSelectedNums.push_back(i); selectNum(k, currentSelectedNums, target - i, result, i+1); // try next num currentSelectedNums.pop_back(); } } };
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解