韩唐伯石 2023-06-06 07:43 采纳率: 55%
浏览 23
已结题

递归中变量的变化问题

力扣第30题中,我使用了一个递归AllComb,但是used的值出现了问题。当使用"barfoothefoobarman", ["foo","bar"]测试时,我最后得到的list只有"foobar"一个元素。我发现是因为递归在从foo bar这个分支返回的时候把bar也推入了used,但按理来说这个used返回的时候就消失了,但结束foo在前面分支,开始bar在前面分支时,那个used已经包含了bar这个元素。这是为什么呢?

//
//                               ""
//                             /    \
//            "foo"                            "bar"
//    /                 \              /                  \
//"foofoo"            "foobar"      "barfoo"          "barbar"
//在递归到第二层bar处时那次迭代的used应该只有foo,但used是["foo","bar"]
//不知道什么原因,bar只在foobar那次推入了那次递归的used,return之后那个used应该已经没了

var findSubstring = function(s, words) {
    let list = [];
    let result = [];

    function AllComb(str, num, used){
        console.log(str);
        if(num === 0){
            list.push(str);
            console.log("!!!");
            return; 
        }

        for(let i = 0; i < words.length; i++){
            console.log("used:",used);
            console.log("i=",i);
            let include = false;

            for(let j = 0; j < used.length; j++){
                if(words[i] === used[j] ){
                    console.log("include:",used[j]);
                    include = true;
                    break;
                }
            }

            if(include === true){
                console.log("跳过")
                continue;
            }
            else{
                used.push(words[i])
                console.log("--------------")
                AllComb(str+words[i],num-1,used);
            }     
        }
    }

    AllComb("", words.length,[]);
    console.log(list);

    for(let i = 0; i < list.length; i++){
        for(let j = 0; j < s.length - list[i].length; j++){
            let counter = 0;
            for(let k = 0; k < list[i].length; k++){
                if(list[i][k] === s[j+k]){
                    counter++
                }
                else{
                    counter = 0;
                }
                if(counter === list[i].length){
                    result.push(j);
                }
            }
        }
    }

    return result;
};
  • 写回答

0条回答 默认 最新

    报告相同问题?

    问题事件

    • 系统已结题 6月14日
    • 创建了问题 6月6日

    悬赏问题

    • ¥15 R语言Rstudio突然无法启动
    • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
    • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
    • ¥15 用windows做服务的同志有吗
    • ¥60 求一个简单的网页(标签-安全|关键词-上传)
    • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
    • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
    • ¥100 为什么这个恒流源电路不能恒流?
    • ¥15 有偿求跨组件数据流路径图
    • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值