Shi*_*vam 11
对于n
对象,存在n!
排列.考虑一组:
S = {a1, a2, a3 ..., an};
Run Code Online (Sandbox Code Playgroud)
查找上述集合的排列的算法可以是:
foreach(item i : S) {
/* all other item except i1 and i */
foreach(item i1 : S - {i}) {
foreach(item i2 : S - {i, i1}) {
.
.
.
foreach(item in : S - {i, i2, .... in-1}) {
/* permutation list */
P = { i1, i2, ...., in-1, in };
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
显然我们不能有n
for
循环,但我们可以递归地构造这个算法,直到我们得到n
列表中的元素P
.下面是使用上述算法进行排列的实际java代码:
public static void
permutations(Set<Integer> items, Stack<Integer> permutation, int size) {
/* permutation stack has become equal to size that we require */
if(permutation.size() == size) {
/* print the permutation */
System.out.println(Arrays.toString(permutation.toArray(new Integer[0])));
}
/* items available for permutation */
Integer[] availableItems = items.toArray(new Integer[0]);
for(Integer i : availableItems) {
/* add current item */
permutation.push(i);
/* remove item from available item set */
items.remove(i);
/* pass it on for next permutation */
permutations(items, permutation, size);
/* pop and put the removed item back */
items.add(permutation.pop());
}
}
Run Code Online (Sandbox Code Playgroud)
这是主要方法:
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());
}
Run Code Online (Sandbox Code Playgroud)
它打印结果:
[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, 3, 1]
[3, 1, 2]
[3, 2, 1]
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
5059 次 |
最近记录: |