面试或笔试中,多次遇到以下4个关于排列组合的手撕算法,这里做个笔记,方法日后查阅:
1. 无重复元素的数组,求全排列;
2. 有重复元素的数组,求全排列;
3. 无重复元素的数组,求组合【子集】;
4. 有重复元素的数组,求组合;
以上四类题,可以用统一的模板实现,如下所示:
package xh.offer.practice;
import java.util.Arrays;
import java.util.HashSet;
import java.util.linkedList;
import java.util.List;
public class listAllGroup{
public static void main(String[] args) {
String [] array = {"1","2"};
String [] repeate = {"1","2","1"};
listAllGroup test = new listAllGroup();
System.out.println("**********no repeate list*******");
test.listAllNoRepeate(Arrays.asList(array),"");//初始化prefix = ""
System.out.println("**********repeate list*******");
HashSet noRepeateSet = new HashSet();
test.listAllRepeate(Arrays.asList(repeate), "", noRepeateSet);
System.out.println("**************no repeate premutation********************");
test.premutationNoRepeate(Arrays.asList(array),"");
System.out.println("*********************repeate premutation**********************");
HashSet repeateSet = new HashSet();
test.premutationRepeate(Arrays.asList(repeate),"", repeateSet);
}
//无重复的组合
public void listAllNoRepeate(List candicate,String prefix){
if(prefix.length() != 0)
System.out.println(prefix);//结果长度不为0,则打印输出该组合
for(int i = 0;i < candicate.size();i++){
//将list转换成linklist链表,方便操作
List tempList = new linkedList(candicate);
//templist减少一个数字,并暂存templist中去除的数字
String tempString = (String) tempList.remove(i);
//递归
listAllNoRepeate(tempList,prefix + tempString);
}
}
//有重复的组合,加入hashset
public void listAllRepeate(List candicate,String prefix,HashSet res){
if(prefix.length() != 0 && !res.contains(prefix)){
System.out.println(prefix);
res.add(prefix);
}
for(int i = 0;i < candicate.size();i++){
List tempList = new linkedList(candicate);
String tempString = tempList.remove(i);
listAllRepeate(tempList, prefix+tempString, res);//递归
}
}
//无重复的全排列,加入判断candicate.size() == 0
public void premutationNoRepeate(List candicate,String prefix){
if(candicate.size() == 0){
System.out.println(prefix);
}
for(int i = 0;i < candicate.size();i++){
List tempList = new linkedList(candicate);
String tempString = tempList.remove(i);
premutationNoRepeate(tempList,prefix+tempString);
}
}
//有重复的全排列,加入hashset辅助判断输出
public void premutationRepeate(List candicate,String prefix,HashSet res) {
if(candicate.size() == 0 && !res.contains(prefix)){
System.out.println(prefix);
res.add(prefix);
}
for(int i = 0;i < candicate.size();i++){
List tempList = new linkedList(candicate);
String tempString = tempList.remove(i);
premutationRepeate(tempList, prefix+tempString, res);
}
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。



