著名软件公司的java笔试算法题及解答

来源:互联网 发布:淘宝注册账号申请手机 编辑:程序博客网 时间:2024/04/28 02:19

用1、2、2、3、4、5这六个数字,用java写一个main函数,打印出所有不同的排列,如:512234、412325等,要求:"4"不能在第三位,"3"与"5"不能相连。

public class test {
    public static void main(String args[]){
     int[] temp = new int[6];
        int[] num = {
            1, 2, 2, 3, 4, 5};
        for (int s1 = 0; s1 < 6; s1++) {
          temp[s1] = num[0];
          for (int s2 = 0; s2 < 6; s2++) {
            if (s2 == s1) {
              continue;
            }
            temp[s2] = num[1];
            for (int s3 = 0; s3 < 6; s3++) {
              if (s3 == s1 || s3 == s2) {
                continue;
              }
              temp[s3] = num[2];
              for (int s4 = 0; s4 < 6; s4++) {
                if(s4==s1 || s4 ==s2 || s4 ==s3){
                  continue;
                }
                temp[s4] = num[3];
                for(int s5=0;s5<6;s5++){
                  if(s5 ==s1 || s5 ==s2 || s5 ==s3 || s5 ==s4){
                    continue;
                  }
                  temp[s5] = num[4];
                  for(int s6=0;s6<6;s6++){
                    if(s6 ==s1 || s6==s2 || s6==s3 || s6==s4 || s6==s5){
                      continue;
                    }
                    temp[s6] = num[5];
                    String pstr = String.valueOf(temp[0])+String.valueOf(temp[1])+String.valueOf(temp[2])+String.valueOf(temp[3])+String.valueOf(temp[4])+String.valueOf(temp[5]);
                    if(!(pstr.indexOf("4")==3 || pstr.indexOf("35")>=0 || pstr.indexOf("53")>=0)) 
                    System.out.println(pstr);
                    else
                    System.out.println("error:"+pstr);
                  }
                }
              }
            }
          }
        }
      }


}

 
原创粉丝点击