Go語言程式:計算給定數字序列的可能解碼數


在 Go 語言中,數字序列是一組用於表示數字的數字。我們可以使用 Go 語言現有的資料型別來表示數字序列。

本文中的 Go 語言程式旨在計算給定數字序列的可能解碼數。它透過使用動態規劃技術來解決此問題。給定一個數字序列,程式計算可以確定數字的方式數量。在這裡,我們將使用 countDecodings 方法以及示例來詳細說明這個概念。

語法

func countDecodings(digits string) int

countDecodings 函式預計將接收一個數字字串作為輸入,並返回一個整數值,該值可能表示該數字序列的可能解碼數。

演算法

  • 定義一個函式來計算可能的解碼數,並以數字序列作為輸入。

  • 如果數字序列為空或只有一個數字,則返回 1,因為只有一種可能的解碼。

  • 建立一個與數字序列長度相同的動態規劃陣列,用於儲存每個位置可能的解碼數。

  • 將動態規劃陣列的前兩個元素初始化為 1,表示前兩個數字有一種可能的解碼。

  • 從第三個數字開始迭代數字序列。

  • 對於每個數字,檢查它是否可以與前一個數字組合形成有效的解碼。如果是,則將前一個位置的解碼數加到動態規劃陣列中當前位置的計數中。

  • 最後,返回動態規劃陣列中最後一個位置的解碼數,它表示給定數字序列的可能解碼總數。

示例

在 countDecodings 函式中,我們首先處理基本情況。如果數字序列為空,我們返回 1 以指示有一種可能的解碼(空字串)。如果第一個數字是 '0',則表示沒有可能的解碼,因此我們返回 0。最後,在主函式中,我們定義一個數字序列,使用該序列呼叫 countDecodings 方法,並列印結果的可能解碼數。

package main

import "fmt"

func countDecodings(digits string) int {
   if len(digits) == 0 {
      return 1
   }

   if digits[0] == '0' {
      return 0
   }

   count := 0

   count += countDecodings(digits[1:])

   if len(digits) >= 2 {
      num := int(digits[0]-'0')*10 + int(digits[1]-'0')
      if num <= 26 {
         count += countDecodings(digits[2:])
      }
   }

   return count
}

func main() {
   digits := "123"
   result := countDecodings(digits)
   fmt.Printf("Number of possible decodings: %d\n", result)
}

輸出

Number of possible decodings: 3

結論

在本文中,我們討論了 Go 語言程式,該程式提供了一種計算給定數字序列的可能解碼數的解決方案。使用動態規劃方法,它透過確定一個數字和兩個決策數字來有效地計算數字。

更新於: 2023年7月20日

76 次瀏覽

開啟你的 職業生涯

完成課程獲得認證

立即開始
廣告

© . All rights reserved.