1. 程式人生 > >Leetcode-1015 Numbers With Repeated Digits(至少有 1 位重復的數字)

Leetcode-1015 Numbers With Repeated Digits(至少有 1 位重復的數字)

bit efi rep dbv div leetcode 當前 註釋 etc

很典型的數位dp,把全球第一的代碼拿過來研究了一下,加了點註釋

代碼作者:waakaaka

個人主頁:https://leetcode.com/waakaaka/

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 #define db(x) cerr << #x << "=" << x << endl
 4 #define db2(x, y) cerr << #x << "=" << x << "," << #y << "=" << y << endl
 5
#define db3(x, y, z) cerr << #x << "=" << x << "," << #y << "=" << y << "," << #z << "=" << z << endl 6 #define dbv(v) cerr << #v << "="; for (auto _x : v) cerr << _x << ", "; cerr << endl 7 #define
dba(a, n) cerr << #a << "="; for (int _i = 0; _i < (n); ++_i) cerr << a[_i] << ", "; cerr << endl 8 typedef long long ll; 9 typedef long double ld; 10 class Solution 11 { 12 public: 13 int n; 14 int dis; 15 //val為當前數值,bs可以看作是vector<int> hash(10)
16 void go(ll val, int bs) 17 { 18 // 當前數值小於題目所給n,非重復的結果數++ 19 if (val <= n) ++dis; 20 //當前數值乘以10大於所給n,直接返回,不然進了下面的循環就乘以10繼續遞歸了 21 if (val * 10 > n) return; 22 for (int i = 0; i <= 9; ++i) 23 { 24 //當前數值為0(bs為零等價於val為零)且加的一個數字還是零,就直接continue,因為不支持前綴零 25 if (!bs && i == 0) continue; // no 0 for first digit 26 //如果要加的數字i和已經有的數字重復,就也continue,不進行遞歸 27 if (bs & (1 << i)) continue; 28 //加上尾數i,然後更新狀態bs,繼續遞歸 29 go(val * 10 + i, bs | (1 << i)); 30 } 31 } 32 int numDupDigitsAtMostN(int N) 33 { 34 dis = 0; 35 n = N; 36 go(0, 0); 37 //dis為不重復的數字的個數 38 return N + 1 - dis; 39 } 40 };

Leetcode-1015 Numbers With Repeated Digits(至少有 1 位重復的數字)