funcminimizedStringLength(s string)int { m := map[int32]struct{}{} for _, i := range s { m[i] = struct{}{} } returnlen(m) }
2717.半有序排序
解题思路
l表示1的位置,r表示n的位置
如果l < r,那么各自移动即可,结果为1+n-r-1
如果l > r,在l移动的过程中,就帮r移动一次,此时次数会再减少一次
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
funcsemiOrderedPermutation(nums []int)int { n := len(nums) l, r := 0, 0 for i := 0; i < n; i++ { if nums[i] == 1 { l = i } if nums[i] == n { r = i } } if r > l { return l + n - r - 1 } return l + n - r - 1 - 1 }
funcmatrixSumQueries(n int, queries [][]int)int64 { vis := [2]map[int]bool{{}, {}} // 0: 行, 1: 列 var ans int64 for i := len(queries) - 1; i >= 0; i-- { t, index, val := queries[i][0], queries[i][1], queries[i][2] if !vis[t][index] { // 没有被赋值过 var remain int if t == 0 { remain = n - len(vis[1]) } else { remain = n - len(vis[0]) } // 这一行/列还剩下 remain 个可以填入的格子 ans += int64(remain * val) vis[t][index] = true } } return ans }
funccount(num1 string, num2 string, minSum int, maxSum int)int { const mod int = 1e9 + 7 f := func(s string)int { // 剪枝 memo := make([][]int, len(s)) for i := range memo { memo[i] = make([]int, min(9*len(s), maxSum)+1) for j := range memo[i] { memo[i][j] = -1 } }
var dfs func(i int, sum int, limitUp bool)int dfs = func(i int, sum int, limitUp bool)int { if sum > maxSum { return0 } if i == len(s) { if sum >= minSum { return1 } return0 } var res int if !limitUp && memo[i][sum] != -1 { return memo[i][sum] }
up := 9 if limitUp { up = int(s[i] - '0') } for d := 0; d <= up; d++ { res = (res + dfs(i+1, sum+d, limitUp && d == up)) % mod } if !limitUp { memo[i][sum] = res } return res } return dfs(0, 0, true) } ans := f(num2) - f(num1) + mod // 避免负数 sum := 0 for _, c := range num1 { sum += int(c - '0') } if minSum <= sum && sum <= maxSum { // x=num1 是合法的,补回来 ans++ } return ans % mod }