The problem of taking stairs in algorithm

A B  1  3  4 
1 "" 

for example, when there are four stairs, there are four situations.

CIxmWj.png

here is the js version I wrote after the code given in the author"s example.

//.

//Number
function NumCopy(num) {
    var copy = num-0;
    return copy;
}

let N = 4, steps = 3, memo = {};
function move(a, b) {
    if([a, b] in memo) {
        return memo[[a, b]];
    }
    if(a>b) {
        return memo[[a, b]] = 0;
    }
    if(a == b) {
        return memo[[a, b]] = 1;
    }
    if(b>a) {
        for(let i=1; i<=steps; iPP) {
            for(let j=1; j<=steps; jPP) {
                cnt += move(NumCopy(a+i), NumCopy(b-j));
            }
        }
    }
    memo[[a, b]] = cnt;
}
let cnt = 0;
console.log(move(0, N));

I don"t know what"s wrong this time?

Mar.16,2021

pay special attention to termination condition and condition branch return . Without reading your code deeply, I think a return


is missing.
let N = 10, steps = 4, memo = {};
function move(a, b) {
    if(a>b) {
        return memo[[a, b]] = 0;
    }
    if(a == b) {
        return memo[[a, b]] = 1;
    }
    let cnt = 0;
    for(let i=1; i<=steps; iPP) {
        for(let j=1; j<=steps; jPP) {
            cnt += move(a+i, b-j);
        }
    }
    memo[[a, b]] = cnt;
    return memo[[a, b]];
}
console.log(move(0, N));
There are two mistakes in

. The first is that let cnt = 0 should be written in the function. After that, if you want to output the result, you should add a return value to the function.

Menu