生成帕斯卡三角形的最佳方法(提到的两种方法)
我有一个 Java 编程作业。
我通过制作一个 nCr 来实现它( http://en.wikipedia.org/wiki/Combination ) 函数然后使用双 for 循环通过打印出来来制作三角形。
但是,该作业要求创建一个不均匀的二维数组,然后通过将前几行中的两个数字相加来填充,然后打印该数组。
我知道我必须按照要求的方式完成作业,但是我有一种小小的感觉(至少对于小三角形来说)我所实现的方法更好。
哪种方法更好?
I have an programming assignment in Java.
I have implemented it by making an nCr ( http://en.wikipedia.org/wiki/Combination ) function then using a double for loop to make the triangle by printing it out.
However, the assignment calls for a uneven 2d array to be created and then populated by adding the two numbers from the previous lines and then printing the array out.
I know I am going to have to do the assignment the way it asks, however I have a small feeling that (at least for small triangles anyway) that the approach I have implemented is better.
Which is the better approach?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为作业所要求的方法会更好。您的方法需要多次乘法来计算三角形的每个元素。对于需要计算的三角形的每一行,该数字都会增加。
然而,赋值方法需要对三角形的每个元素进行一次加法。
I'd think the method called for by the assignment would be better. You're method requires a number of multiplications to calculate each of the elements of the triangle. This number will increase for each row of the triangle you need to calculate.
The assignment's method, however, requires a single addition for each element of the triangle.
如果我理解您的问题,那么您正在尝试比较两种生成帕斯卡三角形的方法:
第二种方法似乎更好。我错过了什么吗?即使您在
nCr
函数中使用记忆功能,这些调用也会产生开销。If I understand your question, you are trying to compare two approaches to generating Pascal's triangle:
nCr
function to populate each cell of the triangle.The second approach seems hands-down better. Am I missing something? Even if you use memoization in your
nCr
function there is overhead in those calls.使用递归
通过使用简单的逻辑
By using recursion
By using simple logic