3 回答

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

TA貢獻1805條經驗 獲得超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貢獻1812條經驗 獲得超5個贊
這是 rici 解決方案(計數)的實現。(輸出是二維切片的形式,每個切片都是一個組合。)
要生成您的示例輸出,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 關注
- 186 瀏覽
添加回答
舉報