LeetCode 2698. 求一个整数的惩罚数 C#
原题链接
中等
作者:
hpstory
,
2023-06-02 22:10:10
,
所有人可见
,
阅读 123
C# 代码
public class Solution {
private static int[] result = new int[1010];
static Solution(){
for (int i = 1; i <= 1000; i++){
char[] ch = (i * i).ToString().ToCharArray();
result[i] = result[i - 1] + (DFS(ch, i, 0, 0) ? i * i : 0);
}
bool DFS(char[] ch, int x, int index, int sum){
if (index == ch.Length){
return sum == x;
}
int t = 0;
for (int i = index; i < ch.Length; i++){
t = t * 10 + ch[i] - '0';
if (DFS(ch, x, i + 1, sum + t)) return true;
}
return false;
}
}
public int PunishmentNumber(int n) {
return result[n];
}
}