生成从0 ... k-1绘制的所有长度为n的字符串

时间:2020-05-11 08:54:18

标签: algorithm data-structures recursive-backtracking

此问题来自Narasimha Karumanchi的“递归和回溯”一章中的“数据结构和算法”。书中给出的算法如下:

让我们假设我们将当前的k进制字符串保留在数组A [0 ... n-1]中。调用函数k-string(n,k)

void k-string(int n, int k) {
  // process all k-ary strings of length m
  if(n < 1)
    printf("%s", A);       // Assume array A is a global variable
  else {
    for(int j=0; j<k; j++){
        A[n-1] = j;
        k-string(n-1, k);
    }
  } 
}

我听不懂算法。就像他们为什么为字符串元素分配整数j一样?

1 个答案:

答案 0 :(得分:1)

package main

import "fmt"

func printResult(A []int, n int) {
    var i int
    for ; i < n; i++ {
        // Function to print the output
        fmt.Print(A[i])
    }
    fmt.Printf("\n")
}

// Function to generate all k-ary strings
func generateK_aryStrings(n int, A []int, i int, k int) {
    if i == n {
        printResult(A, n)
        return
    }
    for j := 0; j < k; j++ {
        // assign j at ith position and try for all other permutations for remaining positions
        A[i] = j
        generateK_aryStrings(n, A, i+1, k)
    }
}

func main() {
    var n int = 4
    A := make([]int, n)

    // Print all binary strings
    generateK_aryStrings(n, A, 0, 3)
    return
}