Recursion 计算表达式的括号组合 @CareerCup

表达式计算(C++ STL 实现) 通过逆波兰式来计算数学中的中缀表达式,例如:3+(4-7*5),主要是处理运算优先级问题。源码里面的注释非常详细,由于基于基本数据类型实现,实用价值较小,用作学习还是很不错的。(支持的符号(半角模式):0123456789 ( ) .(小数点) + - * / !(阶乘) ^(次方)) 立即下载

还没细看,先把代码放在这里


package Recursion;

import java.util.HashMap;

/**
 * Given a boolean expression consisting of the symbols 0,1, &, /, and ^ , and a
 * desired boolean result value result, implement a function to count the number
 * of ways of parenthesizing the expression such that it evaluates to result.
 * 
 * 给出一个包含0,1, &, /, ^符号的表达式,和一个预期结果。实现一个方法来计算有多少种括号
 * 的组合能使得表达式的结果和预期结果一样。
 */
public class S9_11 {

	public enum Term {
		True, False, And, Or, Xor, LeftParen, RightParen
	};

	public static String reduce(String expression, int start, int end) {
		if (start == end) {
			if (expression.charAt(start) == '1') {
				return "1";
			} else if (expression.charAt(start) == '0') {
				return "0";
			}
		}
		int count = 0;
		int i = 0;
		String[] reduced = new String[3];
		int index = 0;
		int left = start;
		int right = start;
		for (i = start; i <= end; i++) {
			if (expression.charAt(i) == '(') {
				if (count == 0) {
					left = i + 1;
				}
				count++;
			} else if (expression.charAt(i) == ')') {
				count--;
				if (count == 0) {
					right = i - 1;
				}
			}
			if (count == 0) {
				reduced[index] = reduce(expression, left, right);
				if (index == 0) {
					reduced[index + 1] = Character.toString(expression
							.charAt(i + 1));
					i += 1;
					left = i + 1;
					right = i + 1;
				}
				index += 2;
			}
		}
		if (reduced[1].equals("&")) {
			if (reduced[0].equals("1") && reduced[2].equals("1")) {
				return "1";
			}
			return "0";
		} else if (reduced[1].equals("|")) {
			if (reduced[0].equals("1") || reduced[2].equals("1")) {
				return "1";
			}
			return "0";
		} else if (reduced[1].equals("^")) {
			if (reduced[0].equals("1") && reduced[2].equals("0")) {
				return "1";
			} else if (reduced[0].equals("0") && reduced[2].equals("1")) {
				return "1";
			}
			return "0";
		}
		return "0";
	}

	public static boolean evaluate(String expression, int start, int end) {
		String result = reduce(expression, start, end);
		if (result == "0") {
			return false;
		} else {
			return true;
		}
	}

	public static boolean isOperator(char c) {
		switch (c) {
		case '&':
		case '|':
		case '^':
			return true;
		default:
			return false;
		}
	}

	public static String insertParensAround(String expression, int ind) {
		int left = 0;
		int right = 0;
		int index = 0;
		int count = 0;
		for (int i = 0; i < expression.length(); i++) {
			if (isOperator(expression.charAt(i))) {
				if (count == ind) {
					index = i;
				}
				count++;
			}
		}
		count = 0;
		for (int i = index - 1; i >= 0; i--) {
			if (expression.charAt(i) == ')') {
				count++;
			} else if (expression.charAt(i) == '(') {
				count--;
			}
			if (count == 0) {
				left = i;
				break;
			}
		}
		count = 0;
		for (int i = index + 1; i <= expression.length(); i++) {
			if (expression.charAt(i) == '(') {
				count++;
			} else if (expression.charAt(i) == ')') {
				count--;
			}
			if (count == 0) {
				right = i;
				break;
			}
		}
		if (left == 0 && right == expression.length() - 1) {
			return expression;
		}
		String newexpression = expression.substring(0, left) + '('
				+ expression.substring(left, right + 1) + ')'
				+ expression.substring(right + 1);
		return newexpression;
	}

	public static int bruteForce(String expression,
			HashMap<String, Boolean> completed, boolean result, boolean[] flags) {
		int count = 0;
		boolean isDone = true;
		if (completed.containsKey(expression)) {
			return 0;
		}

		for (int i = 0; i < flags.length; i++) {
			if (!flags[i]) {
				flags[i] = true;
				String newexpression = insertParensAround(expression, i);
				isDone = false;
				count += bruteForce(newexpression, completed, result, flags);
				flags[i] = false;
			}
		}

		if (isDone) {
			if (evaluate(expression, 0, expression.length() - 1) == result) {
				System.out.println(expression + " = " + result);
				return 1;
			} else {
				System.out.println(expression + " = " + !result);
				return 0;
			}
		}
		completed.put(expression, true);
		return count;
	}

	public static int countR(String exp, boolean result, int start, int end) {
		if (start == end) {
			if (exp.charAt(start) == '1' && result) {
				return 1;
			} else if (exp.charAt(start) == '0' && !result) {
				return 1;
			}
			return 0;
		}
		int c = 0;
		if (result) {
			for (int i = start + 1; i <= end; i += 2) {
				char op = exp.charAt(i);
				if (op == '&') {
					c += countR(exp, true, start, i - 1)
							* countR(exp, true, i + 1, end);
				} else if (op == '|') {
					c += countR(exp, true, start, i - 1)
							* countR(exp, false, i + 1, end);
					c += countR(exp, false, start, i - 1)
							* countR(exp, true, i + 1, end);
					c += countR(exp, true, start, i - 1)
							* countR(exp, true, i + 1, end);
				} else if (op == '^') {
					c += countR(exp, true, start, i - 1)
							* countR(exp, false, i + 1, end);
					c += countR(exp, false, start, i - 1)
							* countR(exp, true, i + 1, end);
				}
			}
		} else {
			for (int i = start + 1; i <= end; i += 2) {
				char op = exp.charAt(i);
				if (op == '&') {
					c += countR(exp, false, start, i - 1)
							* countR(exp, true, i + 1, end);
					c += countR(exp, true, start, i - 1)
							* countR(exp, false, i + 1, end);
					c += countR(exp, false, start, i - 1)
							* countR(exp, false, i + 1, end);
				} else if (op == '|') {
					c += countR(exp, false, start, i - 1)
							* countR(exp, false, i + 1, end);
				} else if (op == '^') {
					c += countR(exp, true, start, i - 1)
							* countR(exp, true, i + 1, end);
					c += countR(exp, false, start, i - 1)
							* countR(exp, false, i + 1, end);
				}
			}
		}
		return c;
	}

	public static int countDP(String exp, boolean result, int start, int end,
			HashMap<String, Integer> cache) {
		String key = "" + result + start + end;
		if (cache.containsKey(key)) {
			return cache.get(key);
		}
		if (start == end) {
			if (exp.charAt(start) == '1' && result == true) {
				return 1;
			} else if (exp.charAt(start) == '0' && result == false) {
				return 1;
			}
			return 0;
		}
		int count = 0;
		if (result) {
			for (int i = start + 1; i <= end; i += 2) {
				char op = exp.charAt(i);
				if (op == '&') {
					count += countDP(exp, true, start, i - 1, cache)
							* countDP(exp, true, i + 1, end, cache);
				} else if (op == '|') {
					count += countDP(exp, true, start, i - 1, cache)
							* countDP(exp, false, i + 1, end, cache);
					count += countDP(exp, false, start, i - 1, cache)
							* countDP(exp, true, i + 1, end, cache);
					count += countDP(exp, true, start, i - 1, cache)
							* countDP(exp, true, i + 1, end, cache);
				} else if (op == '^') {
					count += countDP(exp, true, start, i - 1, cache)
							* countDP(exp, false, i + 1, end, cache);
					count += countDP(exp, false, start, i - 1, cache)
							* countDP(exp, true, i + 1, end, cache);
				}
			}
		} else {
			for (int i = start + 1; i <= end; i += 2) {
				char op = exp.charAt(i);
				if (op == '&') {
					count += countDP(exp, false, start, i - 1, cache)
							* countDP(exp, true, i + 1, end, cache);
					count += countDP(exp, true, start, i - 1, cache)
							* countDP(exp, false, i + 1, end, cache);
					count += countDP(exp, false, start, i - 1, cache)
							* countDP(exp, false, i + 1, end, cache);
				} else if (op == '|') {
					count += countDP(exp, false, start, i - 1, cache)
							* countDP(exp, false, i + 1, end, cache);
				} else if (op == '^') {
					count += countDP(exp, true, start, i - 1, cache)
							* countDP(exp, true, i + 1, end, cache);
					count += countDP(exp, false, start, i - 1, cache)
							* countDP(exp, false, i + 1, end, cache);
				}
			}
		}
		cache.put(key, count);
		return count;
	}

	public static int total(int n) {
		// Function to return (2n) ! / ((n+1)! * n!)

		// To keep the numbers small, we divide by i when possible to do evenly.
		// If not,
		// we store up the remainder and divide when possible.
		long num = 1;
		long rem = 1;
		for (int i = 2; i <= n; i++) {
			num *= (n + i);
			rem *= i;
			if (num % rem == 0) {
				num /= rem;
				rem = 1;
			}
		}
		return (int) num;
	}

	public static int countDPEff(String exp, boolean result, int start,
			int end, HashMap<String, Integer> cache) {
		String key = "" + start + end;
		int count = 0;
		if (!cache.containsKey(key)) {
			if (start == end) {
				if (exp.charAt(start) == '1') {
					count = 1;
				} else {
					count = 0;
				}
			}

			for (int i = start + 1; i <= end; i += 2) {
				char op = exp.charAt(i);
				if (op == '&') {
					count += countDPEff(exp, true, start, i - 1, cache)
							* countDPEff(exp, true, i + 1, end, cache);
				} else if (op == '|') {
					int left_ops = (i - 1 - start) / 2; // parens on left
					int right_ops = (end - i - 1) / 2; // parens on right
					int total_ways = total(left_ops) * total(right_ops);
					int total_false = countDPEff(exp, false, start, i - 1,
							cache) * countDPEff(exp, false, i + 1, end, cache);
					count += total_ways - total_false;
				} else if (op == '^') {
					count += countDPEff(exp, true, start, i - 1, cache)
							* countDPEff(exp, false, i + 1, end, cache);
					count += countDPEff(exp, false, start, i - 1, cache)
							* countDPEff(exp, true, i + 1, end, cache);
				}
			}
			cache.put(key, count);
		} else {
			count = cache.get(key);
		}
		if (result) {
			return count;
		} else {
			int num_ops = (end - start) / 2;
			return total(num_ops) - count;
		}
	}

	public static void main(String[] args) {
		String terms = "0^0|1&1^1|0|1";
		boolean result = true;

		bruteForce(terms, new HashMap<String, Boolean>(), result,
				new boolean[(terms.length() - 1) / 2]);
		System.out.println(countR(terms, result, 0, terms.length() - 1));
		System.out.println(countDP(terms, result, 0, terms.length() - 1,
				new HashMap<String, Integer>()));
		System.out.println(countDPEff(terms, result, 0, terms.length() - 1,
				new HashMap<String, Integer>()));

	}
}


双闭环PWM整流器VOC控制 +SVPWM调制仿真(Simulink仿真实现) 内容概要:本文详细介绍了基于Simulink平台构建的双闭环PWM整流器VOC(虚拟磁链定向控制)与SVPWM(空间矢量脉宽调制)相结合的仿真模型,系统阐述了三相电压型PWM整流器在电压定向控制策略下的建模方法与控制实现。通过设计外环直流电压控制与内环电流控制的双闭环结构,实现了对整流器的高功率因数运行、能量双向流动及动态性能优化的精确调控。结合SVPWM调制技术,有效提升了直流侧电压利用率并显著降低输出电流谐波含量,增强了系统的整体效率与稳定性。该仿真模型适用于新能源发电、电动汽车充电系统、微电网等高性能电能变换应用场景,文档还配套提供了丰富的学习资源与技术支持渠道,便于深入研究与工程实践。; 适合人群:面向电气工程、自动化、电力电子及相关专业的高校学生、科研人员以及从事新能源、智能电网、电力传动等领域研发工作的工程师;尤其适合已具备自动控制理论、电力电子变换技术和MATLAB/Simulink仿真基础的专业人士进一步深化学习与应用。; 使用场景及目标:①深入理解PWM整流器的工作机理及其双闭环控制系统的架构设计;②掌握VOC控制与SVPWM调制的协同工作机制,提升系统动静态响应性能;③支撑科研课题、课程设计、毕业设计或实际工程项目中的整流器控制系统开发与验证;④作为高级电能变换技术的学习范例,促进对现代电力电子系统控制策略的综合理解与创新能力培养。; 阅读建议:建议结合文中提供的百度网盘链接与公众号资源,下载完整的Simulink仿真模型进行实操演练,在MATLAB环境中调整控制器参数并观察仿真结果,深入剖析控制逻辑与系统响应特性;同时可参考同系列资源如PI双闭环控制、电网不平衡工况下的控制策略等案例,开展对比分析与拓展研究,全面提升系统建模与控制设计的综合能力。 立即下载

相关推荐

手把手教你玩转AT32F403A位带操作:像51单片机一样控制GPIO

本文详细介绍了如何在雅特力AT32F403A国产MCU上实现位带操作,像51单片机一样高效控制GPIO。通过实战演示和性能对比,展示了位带操作在实时控制中的优势,包括更快的执行速度和更低的延迟,特别适合工业控制和电机驱动等场景。

weixin_29234509的博客 285

Java代码配置的表达式解析 之 SpEL表达式

背景: 有些场景下,可能需要把一些java代码的表达式,做成配置化的形式,存储到db中;使用时,从db读取,这时候就需要解析java代码表达式。下面简单介绍通过SpEL 表达式 进行解析。 实际使用: /** * value与配置的表达式匹配 * @param value 值 * @param expressionDefinition 表达式 ...

forBurnInG的专栏 1813

聚类分析(超全超详细版)

聚类分析是一种典型的无监督学习, 用于对未知类别的样本进行划分,将它们按照一定的规则划分成若干个类族,把相似(距高相近)的样本聚在同一个类簇中, 把不相似的样本分为不同类簇,从而揭示样本之间内在的性质以及相互之间的联系规律 聚类算法在银行、零售、保险、医学、军事等诸多领域有着广泛的应用 聚类分析基础 聚类分析的概念 聚类分析是根据在数据中发现的描述对象及其关系的信息,将数据对象分组。目的是...

Gfqwy2021 22万+

Recursion n对括号的组合 @CareerCup

看不太习惯书上写的递归,觉得没有自己写的清晰。 这道题唯一要满足的条件就是在任何时候,左括号数量一定要大等于右括号的数量。 package Recursion; import java.util.HashSet; import java.util.Set; /** *Implement an algorithm to print all valid (e.g., properly

1779

硅谷刷屏的ClawdBot,让Mac mini卖爆了!创始人爆料:一人开发、100% AI 写代码

这两天,个人 AI 助手 ClawdBot 席卷硅谷,国内外社交平台上全是关于它的讨论。 在试用后,网友们纷纷给出了很高的评价。“它是迄今为止最伟大的 AI 应用,相当于你 24 小时全天候专属 AI 员工。”Creator Buddy 创始人兼 CEO Alex Finn 盛赞道,“这就是他们 (Anthropic) 希望 Claude Cowork 呈现的样子。”

技术引领业务创新 1584

NVIDIA 2025 Board Design Engineer 校招笔试全解析:从基础门电路到理想放大器设计

本文详细解析了NVIDIA 2025届板级设计工程师校招笔试的核心考点与解题策略。内容涵盖从基础门电路、CMOS实现NOR门,到开关电源CCM/DCM模式波形分析与效率计算,以及理想运放电路设计与稳定性优化。旨在帮助考生构建硬件知识体系,掌握工程思维,顺利通过NVIDIA Board Design Engineer校招笔试。

weixin_29172201的博客 195

问题 A: 计算组合数

题目链接:http://codeup.cn/problem.php?cid=100000595&pid=0 题目描述 编制程序,输入m,n(M>=n>=0)后,计算下列表达式的值并输出: m! ———————— n! (m-n)! 要求将计算阶乘运算的函数写为fact(n),函数返回值的类型为float 输入 m n 输出 对应表达式的值 样例输入 2...

Rhao的博客 419

DeepSeek在实时计算与流处理系统中的突破性实践

对于技术决策者而言,现在正是将DeepSeek实时计算技术纳入企业架构蓝图的关键时机,那些能够率先构建实时智能能力的企业,将在数据驱动的商业竞争中赢得决定性优势。DeepSeek通过创新的流处理架构,成功将复杂事件处理(CEP)的延迟降低到亚秒级,同时保证了计算结果的精确性。DeepSeek研发的神经架构搜索(NAS)与知识蒸馏联合优化框架,可在保持模型精度的前提下,将参数量压缩至原始模型的1/100,实现边缘设备的实时AI推理。随着5G和物联网技术的普及,对实时处理能力的需求将呈指数级增长。

Programming Talk 289

Hard 单词变型成另一个单词 @CareerCup

对起始单词的每一个字母都做替换,把替换后的单词加入到queue中,并同时维护一个Map来记录变化前单词和变化后单词的联系。用来回溯时能打印出路径。 package Hard; import java.util.HashSet; import java.util.LinkedList; import java.util.Map; import java.util.Queue; impor

4761

8.9华为OD机试真题 新系统 - 灯带颜色变换 (Java/Py/C/C++/Js/Go)

8.9华为OD机试真题 新系统 - 灯带颜色变换 (Java/Py/C/C++/Js/Go)

算法大师! 665

置顶必读(1) | 滚雪球学Oracle教程导航帖,带你弯道超车(持续更新中)

什么是数据库管理系统(DBMS),Oracle在行业中的领先地位Oracle数据库的市场竞争与主要应用场景Oracle数据库的核心功能模块与未来技术发展趋势约束的高级应用:主键、唯一性、外键设计与管理表分区、视图、同义词与序列的最佳实践PL/SQL编程的设计哲学,如何高效使用Oracle SQL DeveloperPL/SQL代码调试与优化技巧RAC集群中的高可用性设计,负载均衡与并行查询的配置集群中的缓存一致性管理。

**My Coding Family** 1万+

Hard 找到由其它单词组成的最长单词 @CareerCup

用DFS的那个模板就能做出来,值得注意的是一个词必须被除自己外的其他词组成才行,不能是自己组成自己。 package Hard; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import CtCILibrary.A

3649

面试问题总结——关于YOLO系列(一)

自从刚开始接到的第一个面试开始,到现在为止,陆陆续续也参加了许多场,我像是一个刚从新手村出来的小白,一路的打怪升级刷经验,期间遇到了很多不会的,我都会及时记录总结。 到现在仍然清晰记得,第一次去面试的时候,当时被怼的多惨。。。 说明:本人是非科班出身,本科是机械电子工程专业,硕士期间的研究方向是机器学习和深度学习,因为我的简历上有关于YOLO的项目,所以我着重准备了YOLO系列的面试可能遇到的问题。 决定开启这个面试问题总结的系列,包括YOLO、C++的内容、OpenCV的内容和深度学习方面被提问的问题

boss-dog 1万+

Tree_Graph 判断T2是否为T1的子树 @CareerCup

原文: You have two very large binary trees: T1, with millions of nodes, and T2, with hundreds of nodes. Create an algorithm to decide if T2 is a subtree of T1 译文: 有两棵很大的二叉树:T1有上百万个结点,T2有上百个结点。写

3487

迈瑞BS系列全自动生化分析仪LIS协议接口手册(内含HL7和ASTM)

迈瑞BS系列全自动生化分析仪LIS协议接口手册,内含HL7和ASTM)

复分析 阿尔福斯(Ahlfors) 第三版答案 英文

答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案

Stack_Queue 把栈排序 Sort a stack @CareerCup

原文: 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

3231

汉书HE8,好用的汇编代码编写工具

汉书HE8,好用的汇编代码编写工具早期编写汇编代码所用功能强大

Stack_Queue 猫狗队列问题 Cat dog queue @CareerCup

An animal shelter holds only dogs and cats, and operates ona strictly “first in, first out” basis. People must adopt either the “oldest”(based on arrival time) of all animals at the shelter, or they

3092

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

Recursion 字符串的全排列 String Permutation @CareerCup

字符串全排列的题目,还是套用模板,同样要注意ret的size问题会变化。而且与上一题不同的是不光是要在ret后面添加进新的组合,而且还要移除前面用过的组合。类似一个队列。 另外Java的substring中区间闭合情况是左闭右开 [ ) 所以想把一个字符串拆成两个区间就可以用这一句: for(int j=0; j<=tmp.length(); j++){ // substring

2977

Moderate 判断井字游戏的胜利 @CareerCup

基于要查找的次数来决定是否要预处理。预处理方式按照3进制来做。 另外,检查是否赢了要判断横行,纵列,正反对角线 package Moderate; /** * Design an algorithm to figure out if someone has won in a game of tic-tac-toe. 译文: 设计算法检查某人是否赢得了井字游戏。 *

2970

LinkLists 检查一个链表是否为回文 Check if a linked list is palindrome @CareerCup

Implement a function to check a linked list is a palindrome 检查一个链表是否为回文 思路: 1 Iterative,利用栈,把链表前半段存入栈,再逐个弹栈和链表后半段比较。注意链表长度为奇数的情况!要跳过中间节点! 2 递归! 定义递归函数为 Result rec(LinkedListNode head, int l

2921

Tree_Graph LCA(Lowest Common Ancestor) 最低公共节点 (BST或者一般树) @CareerCup

原文: Design an algorithm and write code to find the first common ancestor of two nodes in a binary tree. Avoid storing additional nodes in a data structure. NOTE: This is not necessarily a binary se

2627

Sorting_Searching 叠罗汉 @CareerCup

类似前面的一道堆箱子 普适的解法是回溯,注意这类是求最值的回溯题。 另一种解法是LIS,先把其中一维排序,然后对剩下的一维进行LIS package Sorting_Searching; import java.util.ArrayList; import java.util.Collections; /** * A circus is designing a tower r

2461

Hard 随机洗牌函数 @CareerCup

第i个元素和index在[0,i]之间的一个数随机交换 package Hard; import CtCILibrary.AssortedMethods; /** * * Write a method to shuffle a deck of cards. It must be a perfect shuffle - in other words, each 52! permu

2421

Sorting_Searching 读入数字流求rank @CareerCup

用BST实现 package Sorting_Searching; import CtCILibrary.AssortedMethods; /** * Imagine you are reading in a stream of integers. Periodically, you wish to be * able to look up the rank of a n

2383

Moderate rand5()产生rand7() @CareerCup

参考这一文 http://hawstein.com/posts/19.10.html 比书上写得好 package Moderate; /** * * Write a method to generate a random number between 1 and 7, given a method that generates a random number betwe

2367

Recursion 硬币组合问题 @CareerCup

非常有意义的一道题,关键的一点要知道DFS是有顺序的,即在DFS中(5,1)和(1,5)是不一样的组合。所以对这道题我的第一种解法就重复算了多次,具体如图所示:当计算f(10)时,DFS给出的结果是9次,但实际上应该是4. 去重的方法是多用一个变量(level)来限制条件。这样能保证在访问对于给定level只会深搜小于等于level的分支。 同样参考了http://hawstein.c

2366

Hard 大文本找两个单词最短距离 @CareerCup

如果只要找一次就用第一种O(n)解法 如果要找多次就多用一个Hashtable,把所有的组合都保存起来 package Hard; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import CtCILibrary.AssortedMethods; /** * You

2363
上一篇: Recursion 叠箱子最高问题 @CareerCup
下一篇: 如何杀死Chrome进程并重启Chrome
chiiis
博客等级 码龄14年 422粉丝 429原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值