Wednesday, July 1, 2015

216. Combination Sum III ------------M. !!!!

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.

Note:

  • All numbers will be positive integers.
  • The solution set must not contain duplicate combinations.

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

就是递归

class Solution {
public:
vector<vector<int>> combinationSum3(int k, int n) {
return helper(k, 1, n);
}

private:
vector<vector<int>> helper(int k, int start, int n) {
if (n <= 0 || start > 9 || k <= 0) {
return {};
}
if (start == n && k == 1) {
return {{start}};
}
vector<vector<int>> res = helper(k, start + 1, n);
vector<vector<int>> res2 = helper(k - 1, start + 1, n - start);
for (auto& line : res2) {
line.push_back(start);
}
res.insert(res.end(), res2.begin(), res2.end());
return res;
}
};





Mistakes:
1: 一开始 没有注意限制条件  1---9的意思。
2:  很傻的是,第二遍。错了好几个地方。  主要是截止条件 没有考虑 {{start}}的情况。 反而是考虑了一堆{}的情况, 应该返回个{{}}。 哎。 我是SB


No comments:

Post a Comment