leetcode241
public class Solution {
public IList<int> DiffWaysToCompute(string input) {
List<int> ret = new List<int>();
for (int i = ; i < input.Length; i++)
{
if (input[i] == '-' ||
input[i] == '*' ||
input[i] == '+')
{
string part1 = input.Substring(, i);
string part2 = input.Substring(i + );
var part1Ret = DiffWaysToCompute(part1);
var part2Ret = DiffWaysToCompute(part2);
foreach (var p1 in part1Ret)
{
foreach (var p2 in part2Ret)
{
int c = ;
switch (input[i])
{
case '+': c = p1 + p2;
break;
case '-': c = p1 - p2;
break;
case '*': c = p1 * p2;
break;
}
ret.Add(c);
}
}
}
}
if (ret.Count == )
{
ret.Add(int.Parse(input));
}
return ret;
}
}
https://leetcode.com/problems/different-ways-to-add-parentheses/#/description
补充一个python的
class Solution:
def diffWaysToCompute(self, input: str) -> 'List[int]':
re = list()
n = len(input)
for i in range(n):
c = input[i]
if c =='+' or c == '-' or c == '*':
left = input[:i]
right = input[i+:]
for l in self.diffWaysToCompute(left):
for r in self.diffWaysToCompute(right):
if c == '+':
re.append(l + r)
elif c == '-':
re.append(l - r)
elif c == '*':
re.append(l * r)
if len(re) == :
re.append(int(input))
return re
实现:
leetcode241的更多相关文章
- [Swift]LeetCode241. 为运算表达式设计优先级 | Different Ways to Add Parentheses
Given a string of numbers and operators, return all possible results from computing all the differen ...
- LeetCode241——Different Ways to Add Parentheses
Given a string of numbers and operators, return all possible results from computing all the differen ...
- leetcode241 为运算表达式设计优先级
class Solution(object): def diffWaysToCompute(self, input): """ :type input: str :rty ...
- Leetcode241.Different Ways to Add Parentheses为运算表达式设计优先级
给定一个含有数字和运算符的字符串,为表达式添加括号,改变其运算优先级以求出不同的结果.你需要给出所有可能的组合的结果.有效的运算符号包含 +, - 以及 * . 示例 1: 输入: "2-1 ...
随机推荐
- QT 中文乱码问题
1. 在main函数中创建完 QApplication对象后马上添加 QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8&qu ...
- 格式化SQL和逆格式SQL
上篇说过SQLyog中的计算合适数据类型的功能,现在说下Navicat格式化SQL和逆格式化SQL 啥也不说了,一看图,一目了然,Beautify SQL(格式化,即变成最美的语句)和Minify S ...
- xftp5+xshell5工具安装包分享
身为开发人员,常常为这两个工具安装包找不到资源为难!尴尬了... 这次专门写篇博客,记录资源,并分享给大家. 上链接: 链接:https://pan.baidu.com/s/1mRNxHhr7F2Q_ ...
- 条款47:请使用traits class表示类型信息
在stl的算法中,我们的希望往往是根据不同的迭代器类型进行不同的更有效率的操作: template<typename IterT, typename DistT> void advance ...
- Django基于form组件实现注册校验
一 基本流程 1 创建form组件对应的类,比如LoginForm 2 前端的三种渲染方式: 渲染方式三种: 1 <form action="" novalidate met ...
- uva12563 Jin Ge Jin Qu hao(01背包)
这是一道不错的题.首先通过分析,贪心法不可取,可以转化为01背包问题.但是这过程中还要注意,本题中的01背包问题要求背包必须装满!这就需要在普通的01背包问题上改动两处,一个是初始化的问题:把dp[0 ...
- Windows vs Linux:\r\n 与 \r
Linux 下文本文件的换行符为 \n Windows 下文本文件的换行符为 \r\n,占两个字节: \r:归位键(CR),ascii 码为 13 \n:换行键(LF),ascii 码位 10 也即单 ...
- C语言的inline
一.inline 关键字用来定义一个类的内联函数,引入它的主要原因是用它替代C中表达式形式的宏定义. 表达式形式的宏定义一例: #define ExpressionName(Var1,Var2) (( ...
- 获得客户端ip
获得客户端ip private function GetIP(){ if(!empty($_SERVER["HTTP_CLIENT_IP"])){ ...
- pip镜像源
pip是用国内镜像源 https://pypi.python.org/http://pypi.douban.com/simple/ http://mirrors.aliyun.com/pypi/sim ...