How can I determine all possible ways a subsequence can be removed from a sequence?

前端 未结 6 2071
执念已碎
执念已碎 2021-01-31 08:29

Given two sequences, A and B, how can I generate a list of all the possible ways that B can be removed from A?

For example, In JavaSc

6条回答
  •  攒了一身酷
    2021-01-31 08:34

    First I would use string. It's easier to manipulate:

    var results = [];
    
    function permute(arr) {
        var cur, memo = [];
    
        for (var i = 0; i < arr.length; i++) {
            cur = arr.splice(i, 1);
            if (arr.length === 0) {
                results.push(memo.concat(cur));
            }
            permute(arr.slice(), memo.concat(cur));
            arr.splice(i, 0, cur[0]);
        }
        return results;
    }
    
    function removeSub(arr, sub) {
        strArray = arr.join(' ');
        if(strArray.includes(sub)){
            return strArray.replace(sub.join(' ')).split(' ');
        }
        return [];
    }
    
    function removeSubSeq(arr, sub) {
        return permute(removeSub(arr, sub));
    }
    

    I have not commented the code, but do not hesitate to ask for clarification. It's not tested, but the idea is in it...

提交回复
热议问题