您好,欢迎访问一九零五行业门户网

Java算法如何实现全排列

算法一基于递归与回溯实现。在排列1,2,3的时候,先由3向上回溯到2发现没有其他可能的情况,再回溯到1,排列为1,3,2再向上回溯到存在其他情况时,即根节点然后再排列以2为第一位的情况,重复上述过程将所有可能结果全部放入res中。
代码:
import java.util.arraylist;import java.util.list; public class h718_1 { static list<list<integer>> res = new arraylist<>(); public static void main(string[] args) { int[] arr = {1,2,3}; h718_1 h2 = new h718_1(); h2.dfs(arr,new arraylist<>()); for (list<integer> re : res) { system.out.println(re); } } public list<list<integer>> dfs( int[] arr,list<integer> list){ list<integer> temp = new arraylist<>(list); if (arr.length == list.size()){ res.add(temp); } for (int i=0;i<arr.length;i++){ if (temp.contains(arr[i])){ continue; } temp.add(arr[i]); dfs(arr,temp); temp.remove(temp.size()-1); } return res; } }
算法二通过交换位置实现全排列:假设集合为{1,2,3,4};
循环交换位置:1和1交换;1和2交换;1和3交换;1和4交换;
每一次交换再通过递归调用更小的集合:
如:第一次1和1交换确定了1在第一位 所以可以看成 {1} + 递归交换{2,3,4};
第一次1和2交换确定了2在第一位 所以可以看成 {2} + 递归交换{1,3,4};
第一次1和3交换确定了3在第一位 所以可以看成 {3} + 递归交换{1,2,4};
第一次1和4交换确定了4在第一位 所以可以看成 {4} + 递归交换{1,2,3};
依次类推。
代码:
import java.util.arraylist;import java.util.arrays;import java.util.list; public class h718_2 { static list<list<integer>> res = new arraylist<>(); public static void main(string[] args) { int[] arr = {1,2,3}; h718_2 h3 = new h718_2(); h3.pailie_swap(0,arr); } public void pailie_swap(int index, int[] arr){ if (arr.length==index){ system.out.println(arrays.tostring(arr)); return; } for (int i = index;i<arr.length;i++){ swap(i,index,arr); pailie_swap(index+1,arr); swap(i,index,arr); } } public void swap(int i,int j ,int[] arr){ int temp = arr[j]; arr[j] = arr[i]; arr[i] = temp; }}
算法三可以通过添加元素来实现全排列:
首先定义一个list 放入第一个元素为; 然后将剩余的元素依次插入之前的集合元素的所有可能的位置生成新的list;
例如:对{1,2,3,4}实现全排列
首先定义一个list 加入第一个元素为 {1}; 然后第二个元素2可以插入{1} 的前后两个位置形成新list :{21,12 }, 第三个元素3分别插入list 的元素的所有位置 为:{321,231,213,312,132,123}; 以此类推。
代码:
import java.util.arraylist; public class h718_3 { public static void main(string[] args) { string aa = "123"; h718_3 h4 = new h718_3(); arraylist<string> res = new arraylist<>(); res = h4.getpermutation0(aa); for (string re : res) { system.out.println(re); } } public arraylist<string> getpermutation0(string a) { int n = a.length(); arraylist<string> res = new arraylist<>(); res.add(a.charat(0) + "");//初始化,包含第一个字符 for (int i = 1; i < n; i++) {//第二个字符插入到前面生成集合的每个元素里面 arraylist<string> res_new = new arraylist<>(); char c = a.charat(i);//新字符 for (string str : res) {//访问上一趟集合中的每个字符串 // 插入到每个位置,形成一个新串 string newstr = c + str;//加在前面 res_new.add(newstr); newstr = str + c;//加在后面 res_new.add(newstr); //加在中间 for (int j = 1; j < str.length(); j++) { newstr = str.substring(0, j) + c + str.substring(j); res_new.add(newstr); } } res = res_new;//更新 } return res; }}
以上就是java算法如何实现全排列的详细内容。
其它类似信息

推荐信息