Cracking the coding interview--Q8.3

Latex | IEEE双栏排版中长公式的排版 IEEE双栏排版中,有时候公式过于长了,过宽,导致单栏排版不下。 阅读详情

原文:

Write a method that returns all subsets of a set.

译文:

写一个函数返回一个集合中的所有子集。


对于一个集合,它的子集一共有2n 个(包括空集和它本身)。它的任何一个子集, 我们都可以理解为这个集合本身的每个元素是否出现而形成的一个序列。比如说, 对于集合{1, 2, 3},空集表示一个元素都没出现,对应{0, 0, 0}; 子集{1, 3},表示元素2没出现(用0表示),1,3出现了(用1表示),所以它对应 {1, 0, 1}。这样一来,我们发现,{1, 2, 3}的所有子集可以用二进制数000到111 的8个数来指示。泛化一下,如果一个集合有n个元素,那么它可以用0到2n -1 总共2n 个数的二进制形式来指示。每次我们只需要检查某个二进制数的哪一位为1, 就把对应的元素加入到这个子集就OK。代码如下:


	/**
	 * @param str
	 * @return
	 * 
	 * 对于一个集合,它的子集一共有2n 个(包括空集和它本身)
	 * 计算所有的子集,如果元素包含n个,则可以使用n位二进制表示,
	 * 
	 * 比如说, 对于集合{1, 2, 3},空集表示一个元素都没出现,对应{0, 0, 0}; 子集{1, 3},表示元素2没出现(用0表示),
	 * 1,3出现了(用1表示),所以它对应 {1, 0, 1}。这样一来,我们发现,{1, 2, 3}的所有子集可以用二进制数000到111 的8个数来指示。
	 * 使用链表记录2n 个结果,其中每个结果都是一个链表记录当前二进制的选择情况
	 * 
	 */
	public static LinkedList<LinkedList<Integer>> getAllSubSet(String []str) {
		LinkedList<LinkedList<Integer>> link = new LinkedList<LinkedList<Integer>>();
		int len = str.length;
		int sum = 1;
		for(int i=0; i< len; i++) {
			sum <<= 1;
		}
		System.out.println("总共子集有 sum = " + sum);
		
		for(int i=0; i<sum; i++) {
			LinkedList<Integer> subList = new LinkedList<Integer>();
			int count = len;
			int sub = i;
			while(count > 0) {
				if((sub & 1) == 1) {
					subList.add(1);
				} else {
					subList.add(0);
				}
				count --;
				sub >>= 1;			
			}
			link.add(subList);
		}
		return link;
	}


解这道题目的另一种思路是递归。这道题目为什么可以用递归? 因为我们能找到比原问题规模小却同质的问题。比如我要求{1, 2, 3}的所有子集, 我把元素1拿出来,然后去求{2, 3}的所有子集,{2, 3}的子集同时也是{1, 2, 3} 的子集,然后我们把{2, 3}的所有子集都加上元素1后,又得到同样数量的子集, 它们也是{1, 2, 3}的子集。这样一来,我们就可以通过求{2, 3}的所有子集来求 {1, 2, 3}的所有子集了。而同理,{2, 3}也可以如法炮制。代码如下:


/**
	 * @param len
	 * @param curIndex
	 * @return
	 * 
	 * 使用递归的方式
	 * 
	 */
	public static LinkedList<LinkedList<Integer>> getAllSubSetByReCursion(int len, int curIndex) {
		 LinkedList<LinkedList<Integer>> subSets = new LinkedList<LinkedList<Integer>>();
		 if(curIndex == len) {
			 LinkedList<Integer> part = new LinkedList<Integer>();
			 subSets.add(part);
		 } else {
			 LinkedList<LinkedList<Integer>> part = getAllSubSetByReCursion(len, curIndex + 1);
			 
			 for(LinkedList<Integer> sub: part) {
				 subSets.add(sub);
				 LinkedList<Integer> newSub = new LinkedList<Integer>();
				 for(Integer temp: sub) {
					 newSub.add(temp);
				 }
				 newSub.add(1);
				 subSets.add(newSub);
			 }
		 }
		 return subSets; 
	}



总代码:

package chapter_8_Recursion;

import java.util.LinkedList;
import java.util.Scanner;

/**
 * 
 * 写一个函数返回一个集合中的所有子集。
 *
 */
public class Question_8_3 {
	
	/**
	 * @param str
	 * @return
	 * 
	 * 对于一个集合,它的子集一共有2n 个(包括空集和它本身)
	 * 计算所有的子集,如果元素包含n个,则可以使用n位二进制表示,
	 * 
	 * 比如说, 对于集合{1, 2, 3},空集表示一个元素都没出现,对应{0, 0, 0}; 子集{1, 3},表示元素2没出现(用0表示),
	 * 1,3出现了(用1表示),所以它对应 {1, 0, 1}。这样一来,我们发现,{1, 2, 3}的所有子集可以用二进制数000到111 的8个数来指示。
	 * 使用链表记录2n 个结果,其中每个结果都是一个链表记录当前二进制的选择情况
	 * 
	 */
	public static LinkedList<LinkedList<Integer>> getAllSubSet(String []str) {
		LinkedList<LinkedList<Integer>> link = new LinkedList<LinkedList<Integer>>();
		int len = str.length;
		int sum = 1;
		for(int i=0; i< len; i++) {
			sum <<= 1;
		}
		System.out.println("总共子集有 sum = " + sum);
		
		for(int i=0; i<sum; i++) {
			LinkedList<Integer> subList = new LinkedList<Integer>();
			int count = len;
			int sub = i;
			while(count > 0) {
				if((sub & 1) == 1) {
					subList.add(1);
				} else {
					subList.add(0);
				}
				count --;
				sub >>= 1;			
			}
			link.add(subList);
		}
		return link;
	}
	
	/**
	 * @param len
	 * @param curIndex
	 * @return
	 * 
	 * 使用递归的方式
	 * 
	 */
	public static LinkedList<LinkedList<Integer>> getAllSubSetByReCursion(int len, int curIndex) {
		 LinkedList<LinkedList<Integer>> subSets = new LinkedList<LinkedList<Integer>>();
		 if(curIndex == len) {
			 LinkedList<Integer> part = new LinkedList<Integer>();
			 subSets.add(part);
		 } else {
			 LinkedList<LinkedList<Integer>> part = getAllSubSetByReCursion(len, curIndex + 1);
			 
			 for(LinkedList<Integer> sub: part) {
				 subSets.add(sub);
				 LinkedList<Integer> newSub = new LinkedList<Integer>();
				 for(Integer temp: sub) {
					 newSub.add(temp);
				 }
				 newSub.add(1);
				 subSets.add(newSub);
			 }
		 }
		 return subSets; 
	}
	
	public static void printAllSubSet(LinkedList<LinkedList<Integer>> link, String []str) {
		for(LinkedList<Integer> temp: link) {
			int index = 0;
			for(Integer t: temp) {
				if(t == 1) {
					System.out.print(" " + str[index] + " ");
				} else {
					System.out.print(" 不获取 ");
				}
				index ++;
			}
			System.out.println();
		}
	}
	
	public static void main(String args[]) {
		String str[] = "hello world china".split(" ");
		LinkedList<LinkedList<Integer>> result = getAllSubSet(str);
		
		printAllSubSet(result, str);
		
		String str2[] = "a b c".split(" ");
		

		 LinkedList<LinkedList<Integer>> result2 = getAllSubSetByReCursion(str2.length, 0);
		 
		 printAllSubSet(result, str2);
	}
}



海思MIPI屏调试实战:从参数计算到点亮屏幕的完整指南 本文提供了一份海思平台MIPI屏幕调试的完整实战指南。文章以Hi3516DV300调试800x1280分辨率屏幕为例,详细讲解了从参数计算、配置文件修改到最终点亮屏幕的全流程,并分享了常见问题排查与进阶优化技巧,旨在帮助嵌入式开发者高效解决MIPI屏调试难题。 阅读详情

相关推荐

H3C交换机S-MLAG实战:如何用bond4模式实现服务器高可用(附避坑指南)

本文详细介绍了H3C交换机S-MLAG技术与服务器bond4模式的实战配置,帮助实现跨设备链路聚合的服务器高可用方案。通过解析S-MLAG技术优势、bond4模式选择、关键配置步骤及常见问题排查,提供了一套完整的避坑指南和优化建议,适用于企业级网络架构的高可用需求。

weixin_30790841的博客 465

Cracking the coding interview--Q4

Chapter 4 | Trees and Graphs 4.1 Implement a function to check if a tree is balanced. For the purposes of this question, a balanced tree is defined to be a tree such that no two leaf nodes differ

763

数字IC设计随笔之二(VCS、DVE|Verdi单步调试)

VCS+Verdi单步调试

ic疾风传 1万+

cracking-the-coding-interview的核心秘密:如何用单元测试“定义”面试题?C++ Catch+Python unittest的TDD完整教程

cracking-the-coding-interview 是一个为《Cracking the Coding Interview》(CTCI)第 6 版提供 **C++ 与 Python 双语言解法** 的开源项目,其最大特色是:**每一道面试题的解法都配有完整的自动化单元测试**(C++ 端用 Catch 框架,Python 端用 unittest 框架),自动化测试覆盖率超过 90%。更妙的是

gitblog_00501的博客 317

【Excel VBA 编程】表格内自动生成进度条

在表格中生成进度条,进度条需要自适应单元格的宽度,根据不同进度区间变换颜色,并且按照进度数据大小显示其长短

wei1019的专栏 1518

Mac用户福音:三步搞定PyMol开源版,告别许可证弹窗(附Homebrew/MacPorts安装指南)

本文为Mac用户提供三步安装PyMol开源版的详细指南,帮助科研人员告别许可证弹窗烦恼。通过Homebrew或MacPorts包管理器安装开源核心,并与商业版图形界面整合,实现无干扰的分子可视化研究体验。特别适合MacOS用户快速部署PyMol进行结构生物学分析。

weixin_28743405的博客 194

Cracking the coding interview--Q9

Chapter 9 | Sorting and Searching 9.1 You are given two sorted arrays, A and B, and A has a large enough buffer at the end to hold B. Write a method to merge B into A in sorted order. 插入排序,需要调整数

1020

奇异值分解(SVD)C++实现

奇异值分解SVD(紧奇异值分解,截断奇异值分解)C++实现

weixin_45804601的博客 4172

Cracking the coding interview--Q17

Chapter 17 | Networking 17.1 Explain what happens, step by step, after you type a URL into a browser. Use as much detail as possible.  先进行DNS的namequery,得到对方的cname或者a记录(当然也可能是IPV6),反正就最后得到对方的IP

630

伺服电机开发实战指南

伺服电机作为工业自动化的核心部件,正经历前所未有的技术革新。本文从基础原理出发,详细介绍了伺服电机的分类、工作原理和特性,分析了伺服电机系统组成与核心部件,探讨了企业级开发技术,包括控制算法、通信协议和故障诊断等高级功能,并提供了实战案例分析,从行业应用到具体开发步骤,展示了伺服电机的工程实现。通过深入理解伺服电机的原理、掌握开发技术、学习应用案例,可以实现伺服系统的高性能开发与应用。

全栈 1675

基于Vivado2025的UltraScale+时序收敛优化实战案例

深入解析在Vivado2025环境中针对UltraScale+架构的时序收敛挑战,结合实际设计案例,分享关键优化策略与操作技巧,显著提升设计性能与收敛效率。vivado2025的更新特性为时序优化带来新机遇。

weixin_33660045的博客 343

Cracking the coding interview--Q20.8

题目 原文: Given a string s and an array of smaller strings T, design a method to search s for each small string in T. 译文

cfanr 1699

【stm32+K210项目】基于K210与STM32协同工作的智能垃圾分类系统设计与实现(完整工程资料源码)

本系统采用SG90舵机Maix Bit摄像头STM32C8T6主控板以及LX_TRIG_MP3_V6.0语音播报模块,构建了一套高效的智能垃圾分类系统,综合运用了图像识别、语音播报及精准控制技术。SG90舵机负责控制垃圾桶的开盖操作。该舵机通过接收PWM信号来实现转动,内部有一个基准电路产生周期为20ms的PWM信号,通过外部脉冲信号的控制(高电平时间在0.5ms至2.5ms之间),使得舵机的输出轴转动到指定位置。舵机内的位置反馈电位计。

嵌入式技术开发 5097

Cracking the coding interview--Q3.6

原文: Write a program to sort a stack in ascending order. You should not make any assumptions about how the stack is implemented. The following are the only functions that should be used to write thi

执子之手 560

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

efm32 入门.pdf

本PDF共计22页,介绍的是操作驱动API,下载与否自己斟酌。

渣基础:比照Hawstein学Cracking the coding interview(1)

《C++ Primer 第五版》书实在是太长,太厚了。总是看了十几页就看累了,坚持不了多久,想了想还是别勉强自己,jued

低端玩家的记录地 949

Camera2Demo

在Camera2 的基础上进行封装,使得Camera2一堆初始化逻辑与Activity分离,降低耦合度,完成预览拍照并保存的操作

Cracking the coding interview--Q9.3

题目 原文: Given a sorted array of n integers that has been rotated an unknown number of times, give an O(log n) algorithm that finds an element in the array. You may assume that the array was originall

cfanr 1620

win10 跳过U8环境检测的IE WebControls.rar

win10 安装u8的时候 提示IE WebControls 不通过,这个工具可以欺骗u8的检查。 跳过U8环境检测的IE WebControls。提示导入失败后,重新检测通过。

Cracking the coding interview--Q1.1

作者:ustcweijie 参考:http://hawstein.com/posts/1.1.html 1. 题目 原文:Implement an algorithm to determine if a string has all unique characters. What if you can not use additional data structures?

蔚蓝天空 546

Cracking the coding interview--Q9.7

原文: A circus is designing a tower routine consisting of people standing atop one another’s shoulders. For practical and aesthetic reasons, each person must be both shorter and lighter than the pers

执子之手 547

Cracking the coding interview--Q2.3

题目 原文: Implement an algorithm to delete a node in the middle of a single linked list, given only access to that node. EXAMPLE Input: the node ‘c’ from the linked list a->b->c->d->e Result: nothin

cfanr 1388

Cracking the coding interview--Q8.8

题目 原文: Write an algorithm to print all ways of arranging eight queens on a chess board so that none of them share the same row, column or diagonal. 译文: 写一个算法打印八皇后在棋盘中所有使任意2个皇后不能处于同一行,同一列或是对角线上的摆

cfanr 1292

Cracking the coding interview--Q3.5

题目 原文: Implement a MyQueue class which implements a queue using two stacks. 译文: 用两个栈实现一个队列MyQueue。 解答 方法

cfanr 1448

Cracking the coding interview Q1.1

最近在看Cracking the coding interview 有一个c++习题版本的,地址地址如下:地址 本人一边看一边尝试着用python写一下 python新手,先练练手

djh512的专栏 1087

Cracking the coding interview--Q3.1

题目 原文: Describe how you could use a single array to implement three stacks. 译文: 描述怎样用一个单独的数组来实现三个栈。 解答 解法一: 将数组划分成3等份,每一份独立的用来实现堆栈。 *第一个堆栈:从 0     至 n/3 *第二个堆栈:从 n/3  至 2n/3 *第三个堆栈:从2n/3 至

cfanr 1451

Cracking the coding interview--Q8.6

题目 原文: Implement the “paint fill” function that one might see on many image editing programs. That is, given a screen (represented by a 2-dimensional array of Colors), a point, and a new color, fill

cfanr 1526
上一篇: Cracking the coding interview--Q8.2
下一篇: Cracking the coding interview--Q8.4
java_wliang
博客等级 码龄15年 19粉丝 82原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值