defifVisited(self, s: str) -> bool: s = ''.join(sorted(s)) if s inself.visited: returnTrue self.visited.add(s) returnFalse
defcalc(self, s: str) -> int: times = Counter(s) ans = (len(s) - times['0']) * self.factor[len(s) - 1] for _, val in times.items(): ans //= self.factor[val] return ans
defcountGoodIntegers(self, n: int, k: int) -> int: self.k = k self.factor = [1] * (n + 1) for i inrange(1, n + 1): self.factor[i] = self.factor[i - 1] * i self.visited = set() base = pow(10, (n - 1) // 2) ans = 0 for i inrange(base, base * 10): prefix = str(i) s = prefix + prefix[::-1][n % 2:] ifself.isOk(s) andnotself.ifVisited(s): ans += self.calc(s) return ans
type solution3273 struct{ n, k int factor []int visited map[string]bool }
funcinit3273(n int, k int) *solution3273 { ans := &solution3273{ n: n, k: k, factor: make([]int, n + 1), visited : map[string]bool{}, } ans.factor[0] = 1 for i := 1; i <= n; i++ { ans.factor[i] = ans.factor[i - 1] * i } return ans }
func(t* solution3273) calc(s string) (ans int64) { times := [10]int{} for i, _ := range s { times[s[i] - '0']++ } ans = int64(t.n - times[0]) * int64(t.factor[t.n - 1]) for _, v := range times { ans /= int64(t.factor[v]) } return }
func(t* solution3273) getFullS(prefix string) string { suffix := []byte(prefix) if t.n % 2 == 1 { suffix = suffix[:len(suffix) - 1] } for i := 0; i < len(suffix) / 2; i++ { suffix[i], suffix[len(suffix) - i - 1] = suffix[len(suffix) - i - 1], suffix[i] } return prefix + string(suffix) }
funccountGoodIntegers(n int, k int) (ans int64) { solution := init3273(n, k) from := int(math.Pow10((n - 1) / 2)) to := from * 10 for i := from; i < to; i++ { s := solution.getFullS(strconv.Itoa(i)) if solution.isOk(s) && !solution.ifVisited(s) { ans += solution.calc(s) } } return }