至少是分析这一问题的两个良好途径。 第一种是发射一枚浮gger。 这往往是最佳办法。 但是,你还可以增加伐木,以追踪所发生的情况。 此处是使用较短输入<代码>abc”(<>/code>)首先添加伐木的结果。
i + 1
allSubseq ([], "abc", 0)
allSubseq ([a], "abc", 1)
> console .log ("a")
allSubseq ([a,b], "abc", 2)
> console .log ("ab")
allSubseq ([a,b,c], "abc", 3)
> console .log ("abc")
allSubseq ([a,c], "abc", 3)
> console .log ("ac")
allSubseq ([b], "abc", 2)
> console .log ("b")
allSubseq ([b,c], "abc", 3)
> console .log ("bc")
allSubseq ([c], "abc", 3)
> console .log ("c")
之后
index + 1
allSubseq ([], "abc", 0)
allSubseq ([a], "abc", 1)
> console .log ("a")
allSubseq ([a,b], "abc", 2)
> console .log ("ab")
allSubseq ([a,b,c], "abc", 3)
> console .log ("abc")
allSubseq ([a,c], "abc", 2)
> console .log ("ac")
allSubseq ([a,c,c], "abc", 3)
> console .log ("acc")
allSubseq ([b], "abc", 1)
> console .log ("b")
allSubseq ([b,b], "abc", 2)
> console .log ("bb")
allSubseq ([b,b,c], "abc", 3)
> console .log ("bbc")
allSubseq ([b,c], "abc", 2)
> console .log ("bc")
allSubseq ([b,c,c], "abc", 3)
> console .log ("bcc")
allSubseq ([c], "abc", 1)
> console .log ("c")
allSubseq ([c,b], "abc", 2)
> console .log ("cb")
allSubseq ([c,b,c], "abc", 3)
> console .log ("cbc")
allSubseq ([c,c], "abc", 2)
> console .log ("cc")
allSubseq ([c,c,c], "abc", 3)
> console .log ("ccc")
这将有助于澄清正在发生什么,以及为什么你不想通过固定的<代码>指数+ 1。
但是,我还要指出更简单的执行:
const call = (fn, ...args) =>
fn (...args)
const subseqs = ([c, ...cs]) =>
c == undefined
? [ ]
: call ((ss = subseqs (cs)) => ss .flatMap (s => c + s) .concat (ss))
const allSubseq = (s) =>
subseqs (s) .filter (Boolean) // remove empty string
console .log (allSubseq ( abcd ))
.as-console-wrapper {max-height: 100% !important; top: 0}
在此,主要休养职能为<代码>下<>分>。 我们在<代码>all Subseq中总结,删除在<代码>下代码>上产生的空洞。 如果你想要保持这一空洞,那么它就更加简单。
我们使用<条码>查询<>代码/代码>,作为在功能体内只包含表述而不是说明的<条码>、<条码>、然后加以使用和再使用的一种方式。 如果这样令人困惑,我们就能够绕过呼吁,用发言和像这样地方变量来做同样的事:
const subseqs = ([c, ...cs]) => {
if (c == undefined) return [ ]
const ss = subseqs (cs)
return ss .flatMap (s => c + s) .concat (ss)
}
In either case, our base case is when the input string is empty, and we return an array containing only the empty string. If it s not, we calculate the subsequences for the tail of the string (everything but the first character) and return first those new subsequences prefixed by the first character and then those subsequences directly.
Note that this function does not print your results to the console, just returns them. This is clearly more flexible. If you want to print them individually, you can do something like console .log (allSubseq ( abcd ) .join (
))
or allSubseq ( abcd ) .forEach (console .log)
.
<><0>1 见。 如何减少小型方案和
2You can view the tweaked source code for i + 1
and index + 1