【问题标题】:permutation for string doesnt work for array of ints字符串的排列不适用于整数数组
【发布时间】: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


【解决方案1】:

您的代码中的问题是,当您满足基本条件时,您正在清除 built 数组。因为 Java 将数组作为引用传递,所以当您尝试在第二次迭代中插入 3 时,您的 built 数组为空。

您应该在传递 built 数组之前对其进行复制

mypermImpl(built+other.charAt(i), leftover, l );

模拟上面一行的行为,在传递它之前创建另一个字符串。

【讨论】:

  • 谢谢你就是这样。我以为我可以重复使用。最终编辑: public static void mypermImpl( List built, List other, List> l){ if (other.size() == 0 ){ l.add( new ArrayList(built )); } for ( int i=0; i leftOver = new ArrayList(other); leftOver.remove(i); List built2 = new ArrayList(built); built2.add(other.get(i)); mypermImpl(built2, leftOver, l); } }
猜你喜欢
  • 1970-01-01
  • 2020-07-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多