【发布时间】:2018-09-26 17:33:26
【问题描述】:
所以我有下面的工作字符串烫发代码
public static List<String> myperm( String s ){
List<String> l = new ArrayList<String>();
mypermImpl("", s, l );
return l;
}
public static void mypermImpl( String built, String other, List<String> l ){
if (other.length() == 0 ){
l.add( built );
}
for ( int i=0; i<other.length(); i++ ){
String leftover = other.substring(0,i) + other.substring(i+1);
mypermImpl(built+other.charAt(i), leftover, l );
}
}
使用“123”调用会返回
123
132
213
231
312
321
问题是如果我使用它作为模型对 int 数组执行相同的操作,我不确定为什么这不起作用,想法?
public static List<List<Integer>> myperm( int [] array ){
List<List<Integer>> l = new ArrayList<List<Integer>>();
List<Integer> other = new ArrayList<Integer>();
for ( int i : array ){
other.add( i );
}
mypermImpl(new ArrayList<Integer>(), other, l );
return l;
}
public static void mypermImpl( List<Integer> built, List<Integer> other, List<List<Integer>> l){
if (other.size() == 0 ){
l.add( new ArrayList(built) );
built.clear();
}
for ( int i=0; i<other.size(); i++ ){
List<Integer> leftOver = new ArrayList<Integer>(other);
leftOver.remove(i);
built.add(other.get(i));
mypermImpl(built, leftOver, l);
}
}
产生以下内容
[1, 2, 3]
[3, 2]
[2, 1, 3]
[3, 1]
[3, 1, 2]
[2, 1]
想法??
谢谢
【问题讨论】:
-
我可以给你发送另一个解决方案还是你想从你的代码中找到错误?
-
在您的整数实现中,如果
other.size==0,则清除built列表。你不会在你的字符串版本中这样做。
标签: arrays string algorithm integer permutation