2698.cpp (627B)
1 class Solution { 2 public: 3 bool canPartition(const string &s, const int target) { 4 if (s == "" && target == 0) return true; 5 if (target < 0) return false; 6 7 int left = 0; 8 for (int i = 0; i < s.size(); i++) { 9 left = left * 10 + s[i] - '0'; 10 if (canPartition(s.substr(i + 1), target - left)) return true; 11 } 12 return false; 13 } 14 15 int punishmentNumber(int n) { 16 int res = 0; 17 for (int i = 1; i <= n; i++) { 18 const int sqr = i * i; 19 if (canPartition(to_string(sqr), i)) res += sqr; 20 } 21 return res; 22 } 23 };