Java 列出所有排列&;整数数组列表中的递归组合
我有一个方法Java 列出所有排列&;整数数组列表中的递归组合,java,algorithm,arraylist,Java,Algorithm,Arraylist,我有一个方法perm1,可以打印字符串中所有字符的排列/组合 // print permutation / combination of the characters of the string s (in order) public static void perm1(String s) { perm1("", s); } private static void perm1(String prefix, String s) { int N = s.length(); if (
perm1
,可以打印字符串中所有字符的排列/组合
// print permutation / combination of the characters of the string s (in order)
public static void perm1(String s) { perm1("", s); }
private static void perm1(String prefix, String s) {
int N = s.length();
if (N == 0) System.out.println(prefix);
else {
System.out.println(prefix);
for (int i = 0; i < N; i++)
perm1(prefix + s.charAt(i), s.substring(0, i) + s.substring(i+1, N));
}
}
这并不像我希望的那样产生所有的排列和组合。使用arraylist[1,2,3],它只打印以下内容:
[]
[1]
[1, 2]
[1, 2, 3]
有谁能告诉我如何修改perm2,以便它可以打印其他预期值,如[2][3][2,3][3,2][2,3,1][2,1,3]等。需要
L=a.size()
应该是一个提示sub
和a
值应保留(它们的位置和值),以便正常工作
下面的代码创建数组列表的新副本并对其进行操作:
public static void perm2(ArrayList<Integer> a) {
ArrayList<Integer> sub = new ArrayList<Integer>();
perm2(sub, a);
}
public static void perm2(ArrayList<Integer> sub, ArrayList<Integer> a) {
int L = a.size();
if (L == 0) System.out.println(sub);
else {
System.out.println(sub);
for (int i = 0; i < L; i++) {
ArrayList<Integer> ab = new ArrayList<Integer>(sub);
ab.add(a.get(i));
ArrayList<Integer> bc = new ArrayList<Integer>(a);
bc.remove(i);
perm2(ab, bc);
}
}
}
publicstaticvoidperm2(arraylista){
ArrayList sub=新的ArrayList();
perm2(sub,a);
}
公共静态void perm2(ArrayList sub,ArrayList a){
int L=a.size();
如果(L==0)System.out.println(sub);
否则{
系统输出打印项次(sub);
对于(int i=0;i
我强烈建议研究谷歌的番石榴套餐:
这个包有非常有用的方法“排列(集合元素)”
此包还包含“Set”类中的“powerSet(Set-Set)”方法
嵌套对powerSet(Set)和置换(Collection)的调用应该使事情变得非常简单。什么是完整的期望输出?如果arraylist是{1,2,3},那么期望的输出是{}、{1}、{2}、{3}、{1,2}、{2,1}、{1,3}、{3,1}、{2,2,3}、{1,3,3}、{1,2}、{-该命令不适用于matterI,因为它是对软件的建议。这似乎朝着正确的方向发展,但它给出了重复的元素[1,2,3][1,2,3][2,3,1][2,3,1][2,1][2,1,3][2,1,3]。我需要取消第二个System.out.println(sub)的注释,以便返回较小的组合,如[1][2][3][1,2][1,3]等。感谢boxed_ul-此解决方案非常适合我的需要!这是一个递归练习,所以它的代价并不重要。。。
public static void perm2(ArrayList<Integer> a) {
ArrayList<Integer> sub = new ArrayList<Integer>();
perm2(sub, a);
}
public static void perm2(ArrayList<Integer> sub, ArrayList<Integer> a) {
int L = a.size();
if (L == 0) System.out.println(sub);
else {
System.out.println(sub);
for (int i = 0; i < L; i++) {
ArrayList<Integer> ab = new ArrayList<Integer>(sub);
ab.add(a.get(i));
ArrayList<Integer> bc = new ArrayList<Integer>(a);
bc.remove(i);
perm2(ab, bc);
}
}
}