对于
n对象,存在
n!排列。考虑一组:
S = {a1, a2, a3 ..., an};查找以上集合的置换的算法可以是:
foreach(item i : S) { foreach(item i1 : S - {i}) { foreach(item i2 : S - {i, i1}) { . . . foreach(item in : S - {i, i2, .... in-1}) { P = { i1, i2, ...., in-1, in };} } }}显然,我们没有
n
for循环,但是可以递归构造此算法,直到获得
nlist中的元素
P。以下是使用上述算法进行置换的实际Java代码:
public static void permutations(Set<Integer> items, Stack<Integer> permutation, int size) { if(permutation.size() == size) { System.out.println(Arrays.toString(permutation.toArray(new Integer[0]))); } Integer[] availableItems = items.toArray(new Integer[0]); for(Integer i : availableItems) { permutation.push(i); items.remove(i); permutations(items, permutation, size); items.add(permutation.pop()); }}这是主要方法:
public static void main(String[] args) { // TODO Auto-generated method stub Set<Integer> s = new HashSet<Integer>(); s.add(1); s.add(2); s.add(3); permutations(s, new Stack<Integer>(), s.size());}它打印了结果:
[1, 2, 3][1, 3, 2][2, 1, 3][2, 3, 1][3, 1, 2][3, 2, 1]



