首页 > 代码库 > lua解上阶梯问题(按指定格式输出具体走法、迭代、递归)

lua解上阶梯问题(按指定格式输出具体走法、迭代、递归)

问题描述

楼梯有n阶台阶,上楼可以一步上1阶,也可以一步上2阶,编一程序列出每一种走法。

思路

注释均在代码中

其它

第一次接触lua,很好的脚本语言

源代码

--[[--------------------------------------------------------------------------
表复制:深复制
--]]--------------------------------------------------------------------------
function table.copy(t)
	local t2 = {};

	for k,v in pairs(t) do
		if type(v) == "table" then
			t2[k] = table.copy(v);
		else
			t2[k] = v;
		end
	end

	return t2;
end

--[[--------------------------------------------------------------------------
格式化:将表转为字符串
用于格式化输出
--]]--------------------------------------------------------------------------
function table.formatout(t, h)
	local out = "";

	for k,v in pairs(t) do
		if type(v) == "table" then

			if k == 1 then
				for i = 1, h do out = string.format("%s%s", out, "  "); end
				out = string.format("%s%s", out, "{\n");
			end
			out = string.format("%s%s", out, table.formatout(v, h+1));

			if k == table.getn(t) then
				for i = 1, h do out = string.format("%s%s", out, "  "); end
				out = string.format("%s%s", out,"},\n");
			end

		else

			if k == 1 then
				for i = 1, h do out = string.format("%s%s", out, "  "); end
				out = string.format("%s%s", out, "{");
			end
			out = string.format("%s%d,", out, v);

			if (k == table.getn(t)) then
				out = string.format("%s%s",out,"},\n");
			end
		end
	end

	return out;
end

--[[--------------------------------------------------------------------------
格式化输出
--]]--------------------------------------------------------------------------
function table.print(t)

	local out = table.formatout(t, 0);
	--去掉最后的",\n"两个字符
	print(string.sub(out, 1, string.len(out)-2));

end


--[[--------------------------------------------------------------------------
@param
	solution_new	@format		{{1,2,1} {2,1,1} {1,1,1,1}}
					@meaning	插入值后的新解
	solution		@format 	{{1,2} {2,1} {1,1,1}}
					@meaning	特定n值下,所有的解,每一个元素为一种解
	value			@format		整数
					@meaning	需要插入的值,如1 2
@exmple
	输入状态:
	solution_new 	== 	{}
	solution 		== 	{{1,2} {2,1} {1,1,1}}
	value	 		=http://www.mamicode.com/=	1>