Leetcode: Combination Sum III
2017-02-07 16:51
363 查看
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.
Example 1:
Input: k = 3, n = 7
Output:
Example 2:
Input: k = 3, n = 9
Output:
Credits:
Special thanks to
@mithmatt for adding this problem and creating all test cases.
Subscribe to see which companies asked this question.
class Solution {
private:
int index_count;
vector<vector<int> > results;
public:
void backtrace(int target, int sum, vector<int>& index, int id, int n, int k)
{
if (sum > target || n > k) {
return;
}
else if (sum == target && n == k) {
vector<int> result;
for(int i = 1; i <= n; ++i)
{
result.push_back(index[i]);
}
results.push_back(result);
return;
}
for (int i = id + 1; i < 10; ++i)
{
index[n+1] = i;
backtrace(target, sum + i, index, i, n+1, k);
}
}
vector<vector<int>> combinationSum3(int k, int n) {
if (k * 9 < n) {
return results;
}
vector<int> index = vector<int>(10, 0);
for (int i = 0; i < 10; ++i) {
index[i] = i;
}
results.clear();
backtrace(n, 0, index, 0, 0, k);
return results;
}
};
n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers.
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]]
Credits:
Special thanks to
@mithmatt for adding this problem and creating all test cases.
Subscribe to see which companies asked this question.
class Solution {
private:
int index_count;
vector<vector<int> > results;
public:
void backtrace(int target, int sum, vector<int>& index, int id, int n, int k)
{
if (sum > target || n > k) {
return;
}
else if (sum == target && n == k) {
vector<int> result;
for(int i = 1; i <= n; ++i)
{
result.push_back(index[i]);
}
results.push_back(result);
return;
}
for (int i = id + 1; i < 10; ++i)
{
index[n+1] = i;
backtrace(target, sum + i, index, i, n+1, k);
}
}
vector<vector<int>> combinationSum3(int k, int n) {
if (k * 9 < n) {
return results;
}
vector<int> index = vector<int>(10, 0);
for (int i = 0; i < 10; ++i) {
index[i] = i;
}
results.clear();
backtrace(n, 0, index, 0, 0, k);
return results;
}
};
相关文章推荐
- leetcode_Combination Sum III
- leetcode:Combination Sum III
- [Leetcode] Combination Sum III
- LeetCode Combination Sum III
- Leetcode_Combination Sum III
- [Leetcode]Combination Sum III
- LeetCode 216 Combination Sum III
- Leetcode: Combination Sum III
- LeetCode Combination Sum III DFS
- leetcode 216 Combination Sum III java 算法
- 【leetcode】Array——Combination Sum I/II/III
- LeetCode[216] Combination Sum III
- Leetcode: Combination Sum III
- 【leetcode】Combination Sum III
- [LeetCode 216] Combination Sum III
- 47 leetcode - Combination Sum III
- [LeetCode] Combination Sum III
- Leetcode NO.216 Combination Sum III
- [LeetCode] Combination Sum III 组合之和之三
- LeetCode No.216 Combination Sum III