Careercup - Facebook面试题 - 6321181669982208

时间:2021-09-23 14:45:14

2014-05-02 09:40

题目链接

原题:

Given a number N, write a program that returns all possible combinations of numbers that add up to N, as lists. (Exclude the N+=N) 

For example, if N= return {{,,,},{,,},{,},{,}}

题目:给定一个正整数N,求出所有的由正整数加起来等于N的可能组合(加数保持升序)。比如N = 4的时候,结果是{{1,1,1,1},{1,1,2},{2,2},{1,3}}。

解法:递归解决即可。

代码:

 // http://www.careercup.com/question?id=6321181669982208
#include <iostream>
#include <vector>
using namespace std; void DFS(int cur, int remain, vector<vector<int> > &result, vector<int> &sum)
{
if (remain == ) {
result.push_back(sum);
return;
}
if (remain < cur) {
return;
} int i;
for (i = cur; i <= remain; ++i) {
if (remain - i != && remain - i < i) {
continue;
}
sum.push_back(i);
DFS(i, remain - i, result, sum);
sum.pop_back();
}
} int main()
{
int n;
vector<int> sum;
vector<vector<int> > result;
int i, j; while (cin >> n && n > ) {
DFS(, n, result, sum); cout << "{" << endl;
for (i = ; i < (int)result.size(); ++i) {
cout << " {";
for (j = ; j < (int)result[i].size(); ++j) {
j ? cout << ", ", : ;
cout << result[i][j];
}
cout << "}" << endl;
}
cout << "}" << endl; sum.clear();
for (i = ; i < (int)result.size(); ++i) {
result[i].clear();
}
result.clear();
} return ;
}