一道java题,网上找来的,还没有来得及验证,学习

本文介绍了一种使用Java实现的特定条件下数字排列组合的算法。该算法需满足4不在第三位,3与5不相邻的限制,并通过不同方法实现,包括图遍历、递归和正则表达式。

  题目如下:用1、2、2、3、4、5这六个数字,用java写一个main函数,打印出所有不同的排列,如:512234、412345等,要求:"4"不能在第三位,"3"与"5"不能相连。
基本思路:
1 把问题归结为图结构的遍历问题。实际上6个数字就是六个结点,把六个结点连接成无向连通图,对于每一个结点求这个图形的遍历路径,所有结点的遍历路径就是最后对这6个数字的排列组合结果集。
2 显然这个结果集还未达到题目的要求。从以下几个方面考虑:
  1. 3,5不能相连:实际要求这个连通图的结点3,5之间不能连通, 可在构造图结构时就满足改条件,然后再遍历图。
  2. 不能有重复: 考虑到有两个2,明显会存在重复结果,可以把结果集放在TreeSet中过滤重复结果
  3. 4不能在第三位: 仍旧在结果集中去除满足此条件的结果。

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
采用二维数组定义图结构,最后的代码是:

import java.util.Iterator;
import java.util.TreeSet;

public class TestQuestion {

private String[] b = new String[]{"1", "2", "2", "3", "4", "5"};
private int n = b.length;
private boolean[] visited = new boolean[n];
private int[][] a = new int[n][n];
private String result = "";
private TreeSet set = new TreeSet();

public static void main(String[] args) {
new TestQuestion().start();
}

private void start() {

// Initial the map a[][]
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i == j) {
a[i][j] = 0;
} else {
    a[i][j] = 1;
}
}
}

// 3 and 5 can not be the neighbor.
a[3][5] = 0;
a[5][3] = 0;

// Begin to depth search.
for (int i = 0; i < n; i++) {
    this.depthFirstSearch(i);
}

// Print result treeset.
Iterator it = set.iterator();
while (it.hasNext()) {
String string = (String) it.next();
// "4" can not be the third position.
if (string.indexOf("4") != 2) {
System.out.println(string);
}
}
}

private void depthFirstSearch(int startIndex) {
visited[startIndex] = true;
result = result + b[startIndex];
if (result.length() == n) {
// Filt the duplicate value.
set.add(result);
}
for(int j = 0; j < n; j++) {
if (a[startIndex][j] == 1 && visited[j] == false) {
depthFirstSearch(j);
} else {
continue;
}
}

// restore the result value and visited value after listing a node.
    result = result.substring(0, result.length() -1);
    visited[startIndex] = false;
}
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 

下面也是基于递归的遍历,不过没有用图结构。
public class Assemble {

public void getAssemble(String result, Vector<Character> source)
{
if ( (result.length() == 3) && (result.charAt(2) == '4') )
return;

if ( result.endsWith("35") || result.endsWith("53"))
return;

if ( result.length() == 6 )
{
System.out.println(result);
return;
}

for (int i=0; i<source.size(); i++)
{
Vector<Character> t = (Vector<Character>)source.clone();
t.remove(i);
getAssemble(result + source.get(i), t);
}
}

/**
 * @param args
 */
public static void main(String[] args) {
// TODO Auto-generated method stub
Assemble as = new Assemble();
Vector<Character> v = new Vector<Character>();
v.add('1'); v.add('2'); v.add('2');
v.add('3'); v.add('4'); v.add('5');
as.getAssemble("", v);

System.out.println("Done");
}

}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

public class Untitled1 {
    public static int count=0;
    public Untitled1() {
    }
    /**
     * 递归处理
     * @param buffer char[]
     * @param col int
     * @param printBuffer char[]
     */
    private static void print(char[] buffer,int col,char[] printBuffer){
        int i,j,z;
        char[] tmpBuffer;
        char[] prnBuffer=new char[6];
        for(i=0; i<buffer.length; i++){
            printBuffer[col]=buffer[i];
            if(printBuffer[2]=='4')
                continue;
            if(col>1){
                if (printBuffer[col] == '5' && printBuffer[col - 1] == '3')
                    continue;
                if (printBuffer[col] == '3' && printBuffer[col - 1] == '5')
                    continue;
            }
            prnBuffer=String.valueOf(printBuffer,0,printBuffer.length).toCharArray();
            if (buffer.length==1){
                System.out.println(prnBuffer);
            }
            tmpBuffer=new char[buffer.length-1];
            for(j=0,z=0; j<buffer.length; j++){
                if (j!=i)
                    tmpBuffer[z++]=buffer[j];
            }                
            if(col<6){
                print(tmpBuffer, col + 1, prnBuffer);
                count++;
            }
        }
    }
    public static void main(String[] args) {
        char[] buffer=new char[]{'1','2','2','3','4','5'};
        char[] printBuffer=new char[6];
        Untitled1 u=new Untitled1();
        u.print(buffer,0,printBuffer);
        System.out.println("总数为:"+u.count);
    }
}

 

////////////////////////////////////////////////////////////////////////////////////////////////////

用正则表达式

import java.io.FileWriter;
import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class Test {
    public static void main(String[] args) throws Exception {
        FileWriter out = new FileWriter("result.txt");
        for (int i = 122345; i <= 543221; i++) {
            String s = String.valueOf(i);
            if (s.indexOf("35") >= 0 || s.indexOf("53") >= 0) {
                continue;
            } else{
                //必须是1,2,3,4,5之间的数字
                Pattern p = Pattern.compile("^[1-5]{6}$");
                Matcher m = p.matcher(s);
                boolean b = m.matches();
                if (b) {
                    //第三位不能为4
                    Pattern pat = Pattern.compile("^[1-5]{2}[^4][1-5]{3}$");
                    Matcher mat = pat.matcher(s);
                    boolean bool = mat.matches();
                    if (bool) {
                        s = s + "/r/n";
                        out.write(s, 0, s.length());
                    }
                }
            }
        }
        out.close();
    }
}

java笔试算法 目录 :envelope: 说明 项目介绍 该文档主要是笔主在学习 Java 的过程中的一些学习笔记,但是为了能够涉及到大部分后端学习所需的技术知识点我也会偶尔引用一些别人的优秀文章的链接。文档大部分内容都是笔者参考书籍以及自己的原创。少部分面试回答参考了其他人已有答案,上面都已注明。 该文档涉及的主要内容包括: Java、 数据结构与算法、计算机网络与数据通信、 操作系统、主流框架、数据存储、架构、面试必备知识点等等。相信不论你是前端还是后端都能在这份文档中收获到东西。 关于转载 如果需要引用到本仓库的一些东西,必须注明转载地址!!!毕竟大多都是手敲的,或者引用的是我的原创文章,希望大家尊重一下作者的劳动:grinning_face_with_big_eyes::grinning_face_with_big_eyes::grinning_face_with_big_eyes:! 如何对该开源文档进行贡献 笔记内容大多是手敲,所以难免会有笔误,你可以帮我找错别字。 很多知识点我可能没有涉及到,所以你可以对其他知识点进行补充。 现有的知识点难免存在不完善或者错误,所以你可以对已有知识点的修改/补充。 为什么要做这个开源文档? 在我们学习Java的时候,很多人会面临我不知道继续学什么或者面试会问什么的尴尬情况(我本人之前就很迷茫:grinning_face_with_smiling_eyes:)。所以,我决定通
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值