classSolution { public: intnumDupDigitsAtMostN(int N){ string n(to_string(N)); int ans = 0; for (int len = 1; len <= n.size()-1; ++len) { int t = 9; int i = len-1; int lastNum = 9; while (i--) { t *= lastNum; lastNum--; } ans += t; } // cout << ans << endl; vector<bool> used(10, false); bool DupDigits = false; for (int i = 0; i < n.size(); ++i) { int t = 0; for (int j = 0; j < n[i]-'0'; ++j) { if (used[j] == false) t++; } if (i == 0) t--; // 首位不能是0 for (int j = n.size()-i-1, lastNum = 10-i-1; j > 0; --j, --lastNum) { t *= lastNum; } ans += t; if (used[n[i] - '0']) // why ?? return N - ans; used[n[i]-'0'] = true; } return N - ans - 1; // N 不包含重复数字,要减去N自身 } };