使用lua语言解出下题,分别用递归、迭代二种方式, 写出详细的代码:
迭代:
楼梯有n阶台阶,上楼可以一步上1阶,也可以一步上2阶,编一程序列出每一种走法。
例:3阶台阶的走法是
{
{ 1, 1, 1, },
{ 1, 2, },
{ 2, 1, },
}
递归:
- function SteupInput( Input,Num )
- if Input==1 then
- print(Num .." 1 ")
- m = m + 1
- elseif Input==2 then
- print(Num .." 1 1")
- print(Num .." 2")
- m = m + 2
- else print("请输入正确的阶层数")
- end
- end
- function Way( InputNnum,Steup )
- if InputNnum<=2 then
- SteupInput(InputNnum,Steup)
- else
- for Num=1,2 do
- Way(InputNnum-Num,Steup .." "..Num)
- end
- end
- end
- print("请输入阶层数")
- m = 0
- i = io.read("*number")
- io.write(Way(i," "))
- print("一共有" ..m.. "方法")
function SteupInput( Input,Num )
if Input==1 then
print(Num .." 1 ")
m = m + 1
elseif Input==2 then
print(Num .." 1 1")
print(Num .." 2")
m = m + 2
else print("请输入正确的阶层数")
end
end
function Way( InputNnum,Steup )
if InputNnum<=2 then
SteupInput(InputNnum,Steup)
else
for Num=1,2 do
Way(InputNnum-Num,Steup .." "..Num)
end
end
end
print("请输入阶层数")
m = 0
i = io.read("*number")
io.write(Way(i," "))
print("一共有" ..m.. "方法")
- function Way( n )
- resultAll = {}
- tempArr1 = {""}
- resultAll[1] = tempArr1
- tempArr2 = {" 1"}
- resultAll[2] = tempArr2
- for i=3,n+1 do
- resultAll[i] = {}
- for j = 1,#(resultAll[i-1]) do
- table.insert(resultAll[i],resultAll[i-1][j].." 1")
- end
- for j = 1,#(resultAll[i-2])do
- table.insert(resultAll[i],resultAll[i-2][j].. " 2")
- end
- end
- for i=1,#resultAll[n+1] do
- print(resultAll[n+1][i])
- end
- end
- print("请输入阶层数")
- n = io.read("number")
- io.write(Way(n))