请选择 进入手机版 | 继续访问电脑版

技术控

    今日:55| 主题:53525
收藏本版 (1)
最新软件应用技术尽在掌握

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

[复制链接]
心动则痛Oath 发表于 2016-10-14 12:23:49
141 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



上一篇:iOS邮箱模糊匹配功能集成
下一篇:Top list of Software Development Life Cycle Risks | David Tzemach
大大大 发表于 2016-10-15 04:20:48
瞄瞄,不忍直视
回复 支持 反对

使用道具 举报

董婷 发表于 2016-10-21 11:53:49
到2016-10-21 走过了年少,脚起了水泡  
回复 支持 反对

使用道具 举报

mengchang 发表于 2016-11-3 06:34:56
大学就是大概学学!
回复 支持 反对

使用道具 举报

*滑动验证:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

我要投稿

推荐阅读

扫码访问 @iTTTTT瑞翔 的微博
回页顶回复上一篇下一篇回列表
手机版/CoLaBug.com ( 粤ICP备05003221号 | 文网文[2010]257号 )

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

返回顶部 返回列表