Careercup - Facebook面试题 - 6321181669982208

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+0=N) 



For example, if N=4 return {{1,1,1,1},{1,1,2},{2,2},{1,3}}

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

解法:递归解决即可。

代码:

 1 // http://www.careercup.com/question?id=6321181669982208

 2 #include <iostream>

 3 #include <vector>

 4 using namespace std;

 5 

 6 void DFS(int cur, int remain, vector<vector<int> > &result, vector<int> &sum)

 7 {

 8     if (remain == 0) {

 9         result.push_back(sum);

10         return;

11     }

12     if (remain < cur) {

13         return;

14     }

15     

16     int i;

17     for (i = cur; i <= remain; ++i) {

18         if (remain - i != 0 && remain - i < i) {

19             continue;

20         }

21         sum.push_back(i);

22         DFS(i, remain - i, result, sum);

23         sum.pop_back();

24     }

25 }

26 

27 int main()

28 {

29     int n;

30     vector<int> sum;

31     vector<vector<int> > result;

32     int i, j;

33     

34     while (cin >> n && n > 0) {

35         DFS(1, n, result, sum);

36         

37         cout << "{" << endl;

38         for (i = 0; i < (int)result.size(); ++i) {

39             cout << "    {";

40             for (j = 0; j < (int)result[i].size(); ++j) {

41                 j ? cout << ", ", 1: 1;

42                 cout << result[i][j];

43             }

44             cout << "}" << endl;

45         }

46         cout << "}" << endl;

47         

48         sum.clear();

49         for (i = 0; i < (int)result.size(); ++i) {

50             result[i].clear();

51         }

52         result.clear();

53     }

54     

55     return 0;

56 }

 

你可能感兴趣的:(Facebook)