posts - 183,  comments - 10,  trackbacks - 0

2010年中兴面试题
编程求解
输入两个整数 n 和 m,从数列1,2,3.......n 中随意取几个数,
使其和等于 m,要求将其中所有的可能组合列出来。

用一个 n 位的数根据其每位是否为 1 来判断是否选择相应的数。

实现:

 1 #include <iostream>
 2 using namespace std;
 3 
 4 void solve(int m, int a[], int n)
 5 {
 6     for (int i = 0; i < (1 << n); ++i)
 7     {
 8         int sum = 0;
 9         int index = 0;
10         int t = i;
11         while (t != 0)
12         {
13             if (t % 2 == 1)
14             {
15                 sum += a[index];
16             }
17             ++index;
18             t /= 2;
19         }
20         if (sum == m)
21         {
22             index = 0;
23             t = i;
24             while (t != 0)
25             {
26                 if (t % 2 == 1)
27                 {
28                     cout << a[index] << ' ';
29                 }
30                 ++index;
31                 t /= 2;
32             }
33             cout << endl;
34         }
35     }
36 }
37 
38 int main()
39 {
40     int a[] = {1234567};
41     int n = 7;
42     int m = 10;
43     solve(m, a, n);
44 
45     return 0;
46 }
posted on 2011-05-15 21:42 unixfy 阅读(376) 评论(0)  编辑 收藏 引用

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理