随笔- 509  文章- 0  评论- 151  阅读- 22万 

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 }
复制代码

 

 posted on   zhuli19901106  阅读(173)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示