3 回答

TA貢獻(xiàn)1884條經(jīng)驗(yàn) 獲得超4個贊
這只是計(jì)數(shù)(以k為基數(shù))。您可以這樣做——將連續(xù)的整數(shù)轉(zhuǎn)換為以k為底的整數(shù)——但這是很多除法和余數(shù),因此您不妨使用更簡單的方法。
從n 個0開始,然后盡可能多地重復(fù):
將所有尾隨的k -1 變?yōu)?,然后將前一個元素加1。如果沒有前面的元素,你就完成了。
如果有助于理解,你可以試試k =10,這是普通的十進(jìn)制計(jì)數(shù)。例如:
3919 → 將尾隨 9 改成 0,1 加 1,結(jié)果 3920
3920 → 末尾沒有 9,0 加一,結(jié)果 3921
...
3999 → 將三個尾隨的 9 變?yōu)?0,將 1 加到 3,結(jié)果 4000

TA貢獻(xiàn)1805條經(jīng)驗(yàn) 獲得超10個贊
試試這個代碼!
代碼 :
n = int(input("Enter value of n :"))
result=[]
for num1 in range(0,n+1):
for num2 in range(0,n+1):
result.append(str(num1)+str(num2))
print(result)
輸出 :
Enter value of n :3
['00', '01', '02', '03', '10', '11', '12', '13', '20', '21', '22', '23', '30', '31', '32', '33']

TA貢獻(xiàn)1812條經(jīng)驗(yàn) 獲得超5個贊
這是 rici 解決方案(計(jì)數(shù))的實(shí)現(xiàn)。(輸出是二維切片的形式,每個切片都是一個組合。)
要生成您的示例輸出,getCombinations(3, 2).
func getCombinations(base, length int) [][]int {
// list of combinations always includes the zero slice
combinations := [][]int{make([]int, length)}
current := make([]int, length)
for {
incrementIndex := length - 1
// zero trailing <base - 1>'s
for current[incrementIndex] == base-1 {
current[incrementIndex] = 0
incrementIndex--
// stop when the next digit to be incremented is "larger"
// than the specified (slice) length
if incrementIndex < 0 {
return combinations
}
}
// increment the least significant non-<base - 1> digit
current[incrementIndex]++
// copy current into list of all combinations
combinations = append(combinations, append([]int{}, current...))
}
}
- 3 回答
- 0 關(guān)注
- 194 瀏覽
添加回答
舉報(bào)