ITeye博客

答复: 公司笔试算法题

thanq · 2011-03-08 11:42 · 编程语言 · Markdown

该公司笔试题就1个,要求在10分钟内作完。 题目如下:用1、2、2、3、4、5这六个数字,用java写一个main函数,打印出所有不同的排列,如:512234、412345等,要求:"4"不能在第三位,"3"与"5"不能相连。 思路1:得到全排列,然后对排列进行甄别


	 	 public static void main(String[] args) {  
	        char buf[]={'1','2','3','4','5','6'};  
	        perm(buf,0,buf.length-1);  
	    }  
	    public static void perm(char[] buf,int start,int end){  
	        if(start==end){//递归出口
	        	test(new String(buf));  
	        }  
	        else{//全排列  
	            for(int i=start;i<=end;i++){    
	                swap(buf, start, i);
	                perm(buf,start+1,end);//后续元素递归全排列  
	                swap(buf, start, i); 
	            }  
	        }  
	    }  
	    static void swap(char[]buf,int start,int end){
	    	char temp=buf[start]; 
            buf[start]=buf[end];  
            buf[end]=temp; 
	    }
	    static void test(String str){//2在6前面,解决两个2的重复问题
	    	if (!str.matches("^..4.*$")&&!str.matches("^.*((35)|(53)).*$")&&str.matches("^.*2.*6.*$")) {
				System.out.println(str.replace('6', '2'));
			}
	    }

思路2:在543221-122345之间的数中甄选:


	    public void test(){
	    	for (Integer i = 122345; i < 543221; i++) {
				String string = i.toString();
				if(!string.matches(".*[06789].*")&&string.matches(".*1.*")&&string.matches(".*2.*2.*")
						&&string.matches(".*3.*")&&string.matches(".*4.*")&&string.matches(".*5.*")
						&&!string.matches("^..4.*$")&&!string.matches("^.*((35)|(53)).*$")){
					System.out.println(string);
				}
			}
	    }

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。