技术控

今日:65| 主题:51389

[其他] Print sums of all subsets of a given set

129 3

立即注册CoLaBug.com会员，免费获得投稿人的专业资料，享用更多功能，玩转个人品牌！

x
Given an array of integers, print sums of all subsets in it. Output sums can be printed in any order.
1. Input : arr[] = {2, 3}
2. Output: 0 2 3 5

3. Input : arr[] = {2, 4, 5}
4. Output : 0 2 4 5 6 7 9 11

We can recursively solve this problem. There are total 2    nsubsets. For every element, we consider two choices, we include it in a subset and we don’t include it in a subset. Below is recursive solution based on this idea.
1. // C++ program to print sums of all possible
2. // subsets.
3. #include<bits/stdc++.h>
4. using namespace std;

5. // Prints sums of all subsets of arr[l..r]
6. void subsetSums(int arr[], int l, int r,
7.                 int sum=0)
8. {
9.     // Print current subset
10.     if (l > r)
11.     {
12.         cout << sum << " ";
13.         return;
14.     }

15.     // Subset including arr[l]
16.     subsetSums(arr, l+1, r, sum+arr[l]);

17.     // Subset excluding arr[l]
18.     subsetSums(arr, l+1, r, sum);
19. }

20. // Driver code
21. int main()
22. {
23.     int arr[] = {5, 4, 3};
24.     int n = sizeof(arr)/sizeof(arr[0]);

25.     subsetSums(arr, 0, n-1);
26.     return 0;
27. }

Output:
Note: We haven’t actually created sub-sets to find their sums rather we have just used recursion to find sum of non-contiguous sub-sets of the given set.
The above mentioned techniques can be used to perform various operations on sub-sets like multiplication, division, XOR, OR, etc, without actually creating and storing the sub-sets and thus making the program memory efficient.
This article is contributed by          Aditya Gupta    . If you like GeeksforGeeks and would like to contribute, you can also write an article using    contribute.geeksforgeeks.orgor mail your article to [email protected] See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.ncorrect, or you want to share more information about the topic discussed above

 瞄瞄，不忍直视

 到2016-10-21 走过了年少，脚起了水泡

mengchang 发表于 2016-11-3 06:34:56
 大学就是大概学学!

*滑动验证: #conqu3r_oc_viewthread_fastpost_content .clickCaptcha{top:-270px;}

• 20+ Awesome Open-Source Android Apps To

The best way to learn is to read and that’s [...]

• 王健林创业三年被告222次，刘强东34岁一夜

大佬的首次创业比你想象中要惨很多，那时候 [...]

• 清科数据：12月投资数量小幅上升 人工智能

12月19日，国务院关于印发“十三五”国家战略性 [...]

• CMU邢波教授主题演讲：医疗决策中的弊病给

有些人的血液里，天生流动着革命和创新的因子， [...]

• 爱上你就是爱上了心痛 微信背景图片

深爱是胸口有雷霆万钧，唇齿之间只有云淡风 [...]

• 2017支付宝五福卡有多少人集齐？集福套路都

前两天看新闻，有媒体称支付宝上已经有50万人集 [...]

• 我的天啊！怎么又缺少了 点击本文领取你的

2.5亿现金红包!腾讯QQ春节红包今日开抢 红包入口 [...]

• 2016化妆品零售总额2222亿 增速连年下滑

【订阅DT电商官方微信“DT电商网”，更多行业数 [...]

• 支付宝集五福提示：对不起 您今天扫福字得

一年一度的集福卡的活动又开始了，可是像我这最 [...]

• 让你像吃薯片一样吃香菇，菇滋菇滋要做菌菇

毫无疑问，健康是零食的大趋势，传统零食如饼 [...]

© 2001-2017 Comsenz Inc. Design: Dean. DiscuzFans.