博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
整数分解
阅读量:4187 次
发布时间:2019-05-26

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

给定一个正整数 n,将其拆分为至少两个正整数的和,并使这些整数的乘积最大化。 返回你可以获得的最大乘积。

示例 1:

输入: 2输出: 1解释: 2 = 1 + 1, 1 × 1 = 1。

示例 2:

输入: 10输出: 36解释: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36。

说明: 你可以假设 不小于 2 且不大于 58。

1、回溯法(对于每一种整数分解形式,计算乘积,结果超时) 

int product = 1; // 乘积	int MaxProduct = 1; // 最大乘积	public int integerBreak(int n)	{		if (n == 2)			return 1;				resolveNum(n, product);		return MaxProduct;	}		/**	 * 整数分解,计算每一种分解形式的乘积(回溯法)	 * @param n 被减数	 * @param sub 减数	 */	void resolveNum(int n, int sub)	{		if (n <= sub) // 一次整数分解完成		{			MaxProduct = Math.max(product*n, MaxProduct);		}		else		{			for (int i=2; i
0) { product *= i; // 本次乘积 resolveNum(n-i, i); product /= i; // 恢复 } } } }

 2、记忆化搜索

int[] dp  = null; // 备忘录	public int integerBreak(int n)	{		if (n == 2)			return 1;				dp = new int[n+1];		return breakInteger(n);	}	int breakInteger(int n)	{		int maxProduct = 0;				if (n == 1)			return 1;				// 如果计算过		if (dp[n] != 0)			return dp[n];				for (int i=1; i<=n; i++)		{			// 分为两种情况,一种是只分成两个部分i和n-i,另一种i和递归breakInteger(n-i)			maxProduct = max(maxProduct, i*breakInteger(n-i), i*(n-i));		}		dp[n] = maxProduct;				return dp[n];	}

 

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

你可能感兴趣的文章
我的MSDN Blog正式开张,欢迎大家访问 [ http://blogs.msdn.com/yizhang/ ]
查看>>
ACM UVa算法题209 Triangular Vertices的解法
查看>>
另一道看上去很吓人的面试题:如何交换a和b两个整数的值,不用额外空间 (Rev. 2)
查看>>
一道看上去很吓人的算法面试题:如何对n个数进行排序,要求时间复杂度O(n),空间复杂度O(1)
查看>>
今天David Solomon的为期三天的Windows Internal培训刚结束
查看>>
转贴:Mark Russinovich的Inside Vista Kernel系列文章,讲到了Vista内核的调度,IO,内存管理,缓存,事务处理,安全等众多新特性
查看>>
转载:如何指定程序在Vista上面需要提升权限运行(Elevated)
查看>>
如何知道可执行文件是32-bit还是64-bit
查看>>
.NET Interop: 从IErrorInfo错误对象获得托管代码的异常信息
查看>>
Microsoft Silverlight正式发布
查看>>
国际化编程中Locale相关概念的一些解释
查看>>
PIA (Primary Interop Assembly) & AIA (Alternate Interop Assembly)简介
查看>>
“妖精”团队———阿里巴巴
查看>>
迟到的感谢——2006最有价值博客的候选人(& 个人回顾)
查看>>
第29回 软件质量度量
查看>>
IT 2007预言
查看>>
怎样让.Net2.0的Membership使用已存在的Sql Server2000/2005数据库
查看>>
ASP.NET2.0 文本编辑器FCKeditor使用方法详解
查看>>
常见的 Web 项目转换问题及解决方案
查看>>
VS2005中使用ClickOnce 部署应用程序的升级
查看>>