java字符串全排列问题

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

public class Sort {

private String[] b = new String[] {"1","2","2","3","4","6"};

private int n = b.length;

private boolean[] visited = new boolean[n];

private int[][] a = new int[n][n];

private String result = "";

private TreeSet<String> set = new TreeSet<String>();

public static void main(String[] args) {
new Sort().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();
System.out.println(string);
}
}

private void depthFirstSearch(int startIndex) {
visited[startIndex] = true;
result = result + b[startIndex];
if (result.length() == n) {
// "4" can not be the third position.

if (result.indexOf(" 4 ") != 2) {
// Filt the duplicate value.

set.add(result);
}
}
for (int j = 0; j < n; j++) {
if (a[startIndex][j] == 1 && visited[j] == false) {
depthFirstSearch(j);
}
}

// restore the result value and visited value after listing a node.

result = result.substring(0, result.length() - 1);
visited[startIndex] = false;
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值