2014-05-06 01:49
原题:
Modify the following code to add a row number for each line is printed public class Test { public static void main(String [] args){ printParenthesis(3); } public static void printParenthesis(int n){ char buffer[] = new char[n*2]; printP(buffer,0,n,0,0); } public static void printP(char buffer[], int index, int n, int open, int close){ if(close == n){ System.out.println(new String(buffer)); }else{ if(open > close){ buffer[index] = ']'; printP(buffer, index+1, n, open, close+1); } if(open < n ){ buffer[index] = '['; printP(buffer,index+1,n,open+1,close); } } } } Expected Output: 1.[][][] 2.[][[]] 3.[[]][] 4.[[][]] 5.[[[]]] What changes needs to be done to accomplish the output expected?
题目:给下面的代码加上一些修改,使得输出的结果能带有序号,如示例中的格式。
解法:代码可能还不太明显,但从结果一看就知道是输出N对括号匹配的所有组合,并且卡塔兰数H(3) = 5,也符合条件。只要加上一个全局的counter,并且在输出语句附近给counter加1,就可以带序号输出了。
代码:
1 // http://www.careercup.com/question?id=6253551042953216 2 public class Test { 3 static int res_count = 0; 4 5 public static void main(String [] args) { 6 printParenthesis(3); 7 } 8 9 public static void printParenthesis(int n) { 10 char buffer[] = new char[n * 2]; 11 res_count = 0; 12 printP(buffer, 0, n, 0, 0); 13 } 14 15 public static void printP(char buffer[], int index, int n, int open, int close) { 16 if(close == n) { 17 System.out.print((++res_count) + "."); 18 System.out.println(new String(buffer)); 19 } else { 20 if (open > close) { 21 buffer[index] = ']'; 22 printP(buffer, index+1, n, open, close + 1); 23 } 24 if (open < n) { 25 buffer[index] = '['; 26 printP(buffer, index + 1, n, open + 1, close); 27 } 28 } 29 } 30 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)