golang - string permutation - 切片边界超出范围

时间:2016-10-29 04:03:28

标签: string go permutation indexoutofboundsexception

Here是此问题的Go Playground代码。

我正在尝试使用递归来编写golang字符串排列 置换函数有两个参数,前缀是空字符串("")和str,它是" abc"。代码在

之下
func main() {
    str := "abc"
    perm("", str)
}

func perm(prefix string, str string) {
    n := len(str)
    fmt.Println(n)
    if n == 0 {
        fmt.Println(prefix)
    } else {
        for i := 0; i < n; n++ {
            perm(prefix+str[i:i+1], str[0:i]+str[(i+1):n])
        }
    }
}

当我运行此代码时,我会看到n的值为3,2,1,0,如预期的那样 我成功地获得了#34; abc&#34;但后来我得到了一个&#34; panic: runtime error: slice bounds out of range&#34;错误。

它从未显示第二轮3,2,1,0所以它甚至没有达到b组合。我觉得如果发生错误就是它到达字符串的c部分,但由于它甚至没有到达b部分,我不确定是什么问题。

1 个答案:

答案 0 :(得分:1)

简单:

for i := 0; i < n; n++ {
                   ^^^
                    ?

n替换为i,该0应该从n-1转移到class NaryNode { int value; NaryNode parent; List<NaryNode> children = new ArrayList<NaryNode>(); NaryNode(int x) { this.value = x; } public void addChild(NaryNode childNode) { childNode.parent = this; this.children.add(childNode); } } public class NaryTree { public NaryNode root = new NaryNode(10); public NaryTree() { root.parent = null; } public void traverseTree(NaryNode rootNode)// depth first { System.out.println(rootNode.value); if (rootNode.children.size() != 0) for (NaryNode ch : rootNode.children) traverseTree(ch); } public static void main(String[] args) { NaryTree mytree = new NaryTree(); NaryNode n2 = new NaryNode(20); NaryNode n3 = new NaryNode(3); NaryNode n4 = new NaryNode(15); NaryNode n5 = new NaryNode(8); NaryNode n6 = new NaryNode(45); NaryNode n7 = new NaryNode(22); NaryNode n8 = new NaryNode(11); NaryNode n9 = new NaryNode(16); NaryNode n10 = new NaryNode(18); NaryNode n11 = new NaryNode(7); mytree.root.addChild(n2); mytree.root.addChild(n3); mytree.root.addChild(n4); n2.addChild(n5); n2.addChild(n6); n2.addChild(n7); n3.addChild(n8); n3.addChild(n9); n3.addChild(n10); n4.addChild(n11); // mytree.traverseTree(mytree.root); int max = Integer.MIN_VALUE; int maxavg = calculateaverage(mytree.root,max); System.out.println(maxavg); } private static int calculateaverage(NaryNode root,int max) { int sum = 0; int count =0; if(root.children.size() == 0) return root.value; for(NaryNode cc : root.children){ sum += calculateaverage(cc,max); count++; } sum = sum/count; if(sum>max) max = sum; return max; } }

Resulting playground