File tree Expand file tree Collapse file tree
Templates/10.Dynamic-Programming Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ class Solution :
2+ def digitDP (self , n : int ) -> int :
3+ s = str (n )
4+
5+ @cache
6+ # pos: 第 pos 个数位
7+ # state: 之前选过的数字集合。
8+ # isLimit: 表示是否受到选择限制。如果为真,则第 pos 位填入数字最多为 s[pos];如果为假,则最大可为 9。
9+ # isNum: 表示 pos 前面的数位是否填了数字。如果为真,则当前位不可跳过;如果为假,则当前位可跳过。
10+ def dfs (pos , state , isLimit , isNum ):
11+ if pos == len (s ):
12+ # isNum 为 True,则表示当前方案符合要求
13+ return int (isNum )
14+
15+ ans = 0
16+ if not isNum :
17+ # 如果 isNumb 为 False,则可以跳过当前数位
18+ ans = dfs (pos + 1 , state , False , False )
19+
20+ # 如果前一位没有填写数字,则最小可选择数字为 0,否则最少为 1(不能含有前导 0)。
21+ minX = 0 if isNum else 1
22+ # 如果受到选择限制,则最大可选择数字为 s[pos],否则最大可选择数字为 9。
23+ maxX = int (s [pos ]) if isLimit else 9
24+
25+ # 枚举可选择的数字
26+ for x in range (minX , maxX + 1 ):
27+ # x 不在选择的数字集合中,即之前没有选择过 x
28+ if (state >> x ) & 1 == 0 :
29+ ans += dfs (pos + 1 , state | (1 << x ), isLimit and x == maxX , True )
30+ return ans
31+
32+ return dfs (0 , 0 , True , False )
You can’t perform that action at this time.
0 commit comments