dha*_*ram 8 java algorithm optimization permutation
我编写了一个程序来查找给定项目列表的所有可能的排列.这恰恰意味着我的程序打印r = 0到n的所有可能的P(n,r)值
以下是代码:
package com.algorithm;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class Permutations<T> {
public static void main(String args[]) {
Permutations<Integer> obj = new Permutations<Integer>();
Collection<Integer> input = new ArrayList<Integer>();
input.add(1);
input.add(2);
input.add(3);
Collection<List<Integer>> output = obj.permute(input);
int k = 0;
Set<List<Integer>> pnr = null;
for (int i = 0; i <= input.size(); i++) {
pnr = new HashSet<List<Integer>>();
for(List<Integer> integers : output){
pnr.add(integers.subList(i, integers.size()));
}
k = input.size()- i;
System.out.println("P("+input.size()+","+k+") :"+
"Count ("+pnr.size()+") :- "+pnr);
}
}
public Collection<List<T>> permute(Collection<T> input) {
Collection<List<T>> output = new ArrayList<List<T>>();
if (input.isEmpty()) {
output.add(new ArrayList<T>());
return output;
}
List<T> list = new ArrayList<T>(input);
T head = list.get(0);
List<T> rest = list.subList(1, list.size());
for (List<T> permutations : permute(rest)) {
List<List<T>> subLists = new ArrayList<List<T>>();
for (int i = 0; i <= permutations.size(); i++) {
List<T> subList = new ArrayList<T>();
subList.addAll(permutations);
subList.add(i, head);
subLists.add(subList);
}
output.addAll(subLists);
}
return output;
}
}
Run Code Online (Sandbox Code Playgroud)
产量
P(3,3) : Count (6) :- [[1, 2, 3], [2, 3, 1], [3, 2, 1], [3, 1, 2], [2, 1, 3], [1, 3, 2]]
P(3,2) : Count (6) :- [[3, 1], [2, 1], [3, 2], [1, 3], [2, 3], [1, 2]]
P(3,1) : Count (3) :- [[3], [1], [2]]
P(3,0) : Count (1) :- [[]]
Run Code Online (Sandbox Code Playgroud)
我的问题是,随着我增加输入列表中的数字.运行时间增加,输入列表中的11个数字后,程序几乎死亡.需要大约2 GB内存才能运行.
我在具有8GB RAM和i5处理器的机器上运行它,因此速度和空间不是问题.
如果有人能帮我写一个更有效的代码,我将不胜感激.
Lou*_*man 15
如果你没有存储它 - 如果你只是在迭代它 - 那么考虑使用Heap的算法(http://www.cut-the-knot.org/do_you_know/AllPerm.shtml上的#3 ) -或者,为了让你的生活更轻松,使用Guava's Collections2.permutations
,它实际上并没有构建整个排列列表 - 它会动态地遍历它们.(披露:我向番石榴捐款.)