1.问题描述:设R={r1,r2,…,rn}是要进行排列的n个元素,其中r1,r2,…,rn可能相同。设计一个算法,列出R的所有不同排列
2.算法思想:利用分治思想,可将R的不同排列,分成r1与r2,r3,…,rn的组合,r2,r3,…,rn的排列又可分成r2与r3,…,rn的组合,以此类推。设R1={r1} R2={r2,…,rn},R1与R2的组合有两种,即R1R2或者R2R1。
package иоо╬╦сие;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class ChongFuYuanSuPaiLie {
public List quanPaiLie(String data){
if (data.length() == 1){
List resultList = new ArrayList();
resultList.add(data);
return resultList;
}else{
StringBuffer totalElemets = new StringBuffer(data);
List oneElementList = new ArrayList();
List resultList = new ArrayList();
for (int i=0;i
String oneElement = totalElemets.substring(i, i+1);
StringBuffer otherElements = totalElemets.delete(i, i+1);
if(oneElementList.contains(oneElement)){
totalElemets = new StringBuffer(data);
continue;
}else{
oneElementList.add(oneElement);
}
List otherElementResultList = quanPaiLie(otherElements.toString());
for (String string : otherElementResultList) {
String resultString_1 = oneElement.concat(string);
String resultString_2 = string.concat(oneElement);
if(!resultList.contains(resultString_1)){
resultList.add(resultString_1);
}
if(!resultList.contains(resultString_2)){
resultList.add(resultString_2);
}
}
totalElemets = new StringBuffer(data);
}
return resultList;
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String data = "aacc";
ChongFuYuanSuPaiLie cfys = new ChongFuYuanSuPaiLie();
for (String string : cfys.quanPaiLie(data)) {
System.out.println(string);
}
System.out.println(cfys.quanPaiLie(data).size());
}
}