问题陈述:
// m is the number, n is upto-length of subsequences
// m = 20125, n =3 should print 201, 202, 205, 212, 215, 225, 012, 015, 125
// m = 20125, n =2 should print 20, 21, 22, 25, 01, 02, 05, 12, 15, 25
// m = 20125, n =1 should print 2, 0, 1, 2, 5
// m = 20125, n =4 should print 2012, 2015, 2125, 0125, 2025
// m = 20125, n =5 should print 20125
下面是在 GoLang 中实现的递归解决方案:
package recursion
import (
"fmt"
"strconv"
)
// m is the number, n is upto-length of subsequences
// m = 20125, n =3 should print 201, 202, 205, 212, 215, 225, 012, 015, 125
// m = 20125, n =2 should print 20, 21, 22, 25, 01, 02, 05, 12, 15, 25
// m = 20125, n =1 should print 2, 0, 1, 2, 5
// m = 20125, n =4 should print 20125
func PrintSubSequence(m int, n int) {
numDigits := digits(m)
if n >= 1 && numDigits >= n { // m != 0
for i := 1; i <= numDigits-n+1; i++ { // tree recurion
firstInvocToIter := true
var slice []string
var findSubSequence func(int, int)
findSubSequence = func(m int, n int) {
if n == 1 { // base case
for m != 0 {
slice = append(slice, strconv.Itoa(m%10))
m = m / 10
}
return
} else {
if firstInvocToIter {
firstInvocToIter = false
findSubSequence(m/tenToThePower(i), n-1)
} else {
findSubSequence(m/10, n-1)
}
for i, value := range slice {
slice[i] = value + strconv.Itoa(m%10)
}
}
}
findSubSequence(m, n) // (20125, 3)
fmt.Println(slice)
}
} else {
return
}
PrintSubSequence(m/10, n)
}
这是否需要维护一组字符串?包含slice在一个集合中
或者
如何处理重复?看起来n==1树递归的基本情况有问题?
largeQ
MM们
相关分类