登录
首页 >  Golang >  Go问答

关键见解:最大子序列

来源:stackoverflow

时间:2024-03-24 12:51:39 261浏览 收藏

本问题有两个关键见解: * **区分使用个位数字和不使用个位数字的情况:**使用个位数字时,需要减少 `l`,因为我们使用了一位数字;不使用个位数字时,`l` 不变。 * **使用个位数字时,需要将数字放回末尾:**使用个位数字 `d` 后,需要将 `d` 附加到数字 `n` 的末尾,即 `10 * n + d`。

问题内容

下面是使用树递归方法的问题分配:

最大子序列 数字的子序列是数字的一系列(不一定是连续的)数字。例如,12345 的子序列包括 123、234、124、245 等。您的任务是获取低于特定长度的最大子序列。

def max_subseq(n, l):
    """
    return the maximum subsequence of length at most l that can be found in the given number n.
    for example, for n = 20125 and l = 3, we have that the subsequences are
        2
        0
        1
        2
        5
        20
        21
        22
        25
        01
        02
        05
        12
        15
        25
        201
        202
        205
        212
        215
        225
        012
        015
        025
        125
    and of these, the maxumum number is 225, so our answer is 225.

    >>> max_subseq(20125, 3)
    225
    >>> max_subseq(20125, 5)
    20125
    >>> max_subseq(20125, 6) # note that 20125 == 020125
    20125
    >>> max_subseq(12345, 3)
    345
    >>> max_subseq(12345, 0) # 0 is of length 0
    0
    >>> max_subseq(12345, 1)
    5
    """
    "*** your code here ***"

这个问题有两个关键见解

  • 您需要区分使用个位数字的情况和不使用个位数字的情况。在这种情况下,我们希望减少 l,因为我们使用了其中一位数字,而在不是这种情况下,我们则不这样做。
  • 如果我们使用个位数字,则需要将数字放回末尾,将数字 d 附加到数字 n 的末尾的方法是 10 * n + d

我无法理解这个问题的见解,提到以下两点:

  1. 分为使用个位和不使用个位的情况

  2. 如果我们使用个位数字,您需要将该数字放回末尾

我对这个问题的理解:

此问题的解决方案是生成 l 之前的所有子序列,伪代码如下所示:

digitSequence := strconv.Itoa(n) // "20125"

printSubSequence = func(digitSequence string, currenSubSequenceSize int) { // digitSequence is "20125" and currenSubSequenceSize is say 3
        printNthSubSequence(digitSequence, currenSubSequenceSize) + printSubSequence(digitSequence, currenSubSequenceSize-1)
    }

其中 printnthsubsequence 打印 (20125, 3)(20125, 2) 等的子序列...

在所有这些序列中找到 max_subseq 就变得很容易

您能否通过示例(例如 20125、1)帮助我理解此问题中给出的见解?这是完整的问题


解决方案


有这样的事吗?按照说明的建议,尝试使用或不使用当前数字:

function f(s, i, l){
  if (i + 1 <= l)
    return Number(s.substr(0, l));

  if (!l)
    return 0;
    
  return Math.max(
    // With
    Number(s[i]) + 10 * f(s, i - 1, l - 1),
    // Without
    f(s, i - 1, l)
  );
}

var input = [
  ['20125', 3],
  ['20125', 5],
  ['20125', 6],
  ['12345', 3],
  ['12345', 0],
  ['12345', 1]
];

for (let [s, l] of input){
  console.log(s + ', l: ' + l);
  console.log(f(s, s.length-1, l));
  console.log('');
}

理论要掌握,实操不能落!以上关于《关键见解:最大子序列》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>