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

技术控

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

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

[复制链接]
心动则痛Oath 发表于 2016-10-14 12:23:49
156 3
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-15 04:20:48
瞄瞄,不忍直视
回复 支持 反对

使用道具 举报

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

使用道具 举报

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

使用道具 举报

我要投稿

回页顶回复上一篇下一篇回列表
手机版/c.CoLaBug.com ( 粤ICP备05003221号 | 文网文[2010]257号 | 粤公网安备 44010402000842号 )

© 2001-2017 Comsenz Inc.

返回顶部 返回列表