答复: 公司笔试算法题

该公司笔试题就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);
}
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值