博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
输出一个集合所有子集的元素和(Print sums of all subsets of a given set)
阅读量:4097 次
发布时间:2019-05-25

本文共 2250 字,大约阅读时间需要 7 分钟。

原文地址:

Given an array of integers, print sums of all subsets in it. Output sums can be printed in any order.

Input : arr[] = {2, 3}Output: 0 2 3 5Input : arr[] = {2, 4, 5}Output : 0 2 4 5 6 7 9 11
Method 1 (Recursive)
We can recursively solve this problem. There are total 2
n subsets. 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.

方法一(递归)

我们可以递归地解决这个问题,这个集合共有2n个子集。对于每一个元素,我们考虑两种选择,子集中包含这个元素或者不包含这个元素。下面是基于这个想法的递归方法。

// C++ program to print sums of all possible// subsets.#include
using namespace std; // Prints sums of all subsets of arr[l..r]void subsetSums(int arr[], int l, int r, int sum=0){ // Print current subset if (l > r) { cout << sum << " "; return; } // Subset including arr[l] subsetSums(arr, l+1, r, sum+arr[l]); // Subset excluding arr[l] subsetSums(arr, l+1, r, sum);} // Driver codeint main(){ int arr[] = {5, 4, 3}; int n = sizeof(arr)/sizeof(arr[0]); subsetSums(arr, 0, n-1); return 0;}

Output:

12 9 8 5 7 4 3 0
Method 2 (Iterative)
As discussed above, there are total 2
n subsets. The idea is generate loop from 0 to 2
n – 1. For every number, pick all array elements which correspond to 1s in binary representation of current number.

方法二(迭代)

正如前面所讨论的,这个集合有2n个子集。这个想法就是从0到2n – 1循环。对于每个数字,挑出所有的数组元素,这些元素表示出二进制的时候每一位全部是1.

// Iterative C++ program to print sums of all// possible subsets.#include
using namespace std; // Prints sums of all subsets of arrayvoid subsetSums(int arr[], int n){ // There are totoal 2^n subsets long long total = 1<

Output:

12 9 8 5 7 4 3 0

Thanks to cfh for suggesting above iterative solution in a comment.

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.

注意:我们还没有真正创建子集来得到它们的值,而是我们只是用递归得到已知集合子集的非连续和。

以上所提到的技术可以用于各种子集的操作,例如:乘法、除法、XOR、OR等,没有真正创建并存储子集,因此可以使得代码使用内存更有效。

转载地址:http://cgqii.baihongyu.com/

你可能感兴趣的文章
C++ 写时拷贝 2
查看>>
Linux网络编程---I/O复用模型之poll
查看>>
Java NIO详解
查看>>
单列模式-编写类ConfigManager读取属性文件
查看>>
java中float和double的区别
查看>>
Statement与PreparedStatement区别
查看>>
Tomcat配置数据源步骤以及使用JNDI
查看>>
before start of result set 是什么错误
查看>>
(正则表达式)表单验证
查看>>
在JS中 onclick="save();return false;"return false是
查看>>
JSTL 常用标签总结
查看>>
内容里面带标签,在HTML显示问题,JSTL
查看>>
VS编译器运行后闪退,处理方法
查看>>
用div+css做下拉菜单,当鼠标移向2级菜单时,为什么1级菜单的a:hover背景色就不管用了?
查看>>
idea 有时提示找不到类或者符号
查看>>
JS遍历的多种方式
查看>>
ng-class的几种用法
查看>>
node入门demo-Ajax让前端angularjs/jquery与后台node.js交互,技术支持:mysql+html+angularjs/jquery
查看>>
神经网络--单层感知器
查看>>
注册表修改DOS的编码页为utf-8
查看>>