yuancf1024
yuancf1024

Reputation: 67

panic: runtime error: index out of range [-1]

when I try to solve the leetcode problem of 118. Pascal's Triangle https://leetcode.com/problems/pascals-triangle/

it occured strange bug. Below the code can pass OJ.

func generate(numRows int) [][]int {
    res := [][]int{}
    for i := 0; i < numRows; i++ {
        row := []int{}
        for j := 0; j < i+1; j++ {
            if j == 0 || j == i {
                row = append(row, 1)
            } else if i > 1 {
                row = append(row, res[i-1][j-1] + res[i-1][j])
            }
        }
        res = append(res, row)
    }
    return res
}

But the code I write like this and it occur panic, but the basic logic is same.

func generate(numRows int) [][]int {
    res := [][]int{}
    for i := 0; i < numRows; i++ {
        row := []int{}
        for j := 0; j < i+1; j++ {
            if j == 0 || j == i {
                row = append(row, 1)
            }
            if i > 1 {
                row = append(row, res[i-1][j-1] + res[i-1][j])
            }
        }
        res = append(res, row)
    }
    return res
}

I used if else if structure, it works fine, but I use 2 if condition judgment error.

In fact, their logic is the same, but why the error? I would be grateful if you could solve this problem. Good lcuk for you!

Upvotes: 0

Views: 1926

Answers (1)

The Fool
The Fool

Reputation: 20448

The problem is that you use 2 if conditions in the second version, while in the first version you have an if else.

but the basic logic is same

No, the logic is not the same. The result is that you try to do j-1 when j is 0.

If you have 2 if conditions like this, the program will enter both blocks individually if their respective condition is met.

if j == 0 || j == i {
    row = append(row, 1)
}
// if j is 0 you still enter this block as long as i > 1
if i > 1 {
    row = append(row, res[i-1][j-1] + res[i-1][j])
}

You could use continue to skip this section, if the first if is met.

if j == 0 || j == i {
    row = append(row, 1)
    // continue with the next iteration
    continue
}
if i > 1 {
    row = append(row, res[i-1][j-1] + res[i-1][j])
}

That said, using the if else in the first version of your code seems reasonable. I am not sure why you would want to change it.

Upvotes: 2

Related Questions