ruby 实现了杨辉三角
http://blog.csdn.net/elvaloving/article/details/7082585递归思想
每一行我看做是一个数组,传入的参数是上一个数组,当然每一个结果数组用temp缓存一下,
每传入一个数组,那么打印一次,也就是每行的结果了,
代码class Sanjiao
def initialize(row)
@row = row
end
def sanjiaoxing(temp)
number = temp.length
temp.each do |x|
print x.to_s+' '
end
array = Array.new(number.to_i+1)
0.upto(number.to_i) do |x|
if x == 0 #两端的就不用求了,
array =1
elsifx == number.to_i
array = 1
else
array=temp.to_i+temp.to_i #根据上一个数组的结果得下一数组的值
end
end
temp = array #hauncunyixia
puts " "
if number.to_i < @row
sanjiaoxing(temp)
end
end
end
temp = Array.new(1)
temp =1
p = Sanjiao.new(20)
p.sanjiaoxing(temp)
页:
[1]