您的位置:首页 > 其它

leetcode 216: Combination Sum III

2015-05-30 10:22 246 查看
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.
Ensure that numbers within the set are sorted in ascending order.

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]]
[思路]
因为k是不定的, 所以无法用LOOP. 递归是此类题的常用解法. 为了方便, 多用一个variable: sum保存当前cur中所有数的和. 注意要新建一个list 放入结果中, 否则放入的reference 会指向原来的不断变化的list, res.add(new ArrayList(cur));

[CODE]
class Solution {
public:
void visit(int pos, int k, int n, int &sum,  vector<int> &buf, vector<vector<int> > &result)
{
if (k == 0)
{
if (sum == n)
{
result.push_back(buf);
}
return;
}
for (int i = pos; i <= 9; i++)
{
if (sum + i > n)
{
break;
}
buf.push_back(i);
sum += i;
visit(i+1, k-1, n, sum, buf, result);
buf.pop_back();
sum -= i;
}
}

vector<vector<int>> combinationSum3(int k, int n) {
vector<vector<int> > result;
vector<int> buf;
int sum = 0;
visit(1, k, n, sum, buf, result);
return result;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: