2020-04-13 11:38:31
問題の説明:
整数nが与えられた場合、n以下のすべての非負の整数における数1の出現数を数えます。
例:
入力:13
出力:6
説明:数値1は、1、10、11、12、13の中に現れます。
問題解決:
デジタルdpは、効率的なソリューションに使用できます。
dp [pos] [cnt]:現在の数字の前にあるcnt 1の合計と、取得できる1の合計数。
int [] digits = new int [64]; int [] [] dp = new int [64] [64]; public int countDigitOne(int n){ if(n <= 0)return 0; int pos = 0; while(n> 0){ digits [pos ++] = n%10; n / = 10; } return dfs(pos-1、0、true); } public int dfs(int pos、int cnt、boolean limit){ if(pos == -1)return cnt; if(!limit && dp [pos] [cnt]!= 0)return dp [pos] [cnt]; int up = limit?digits [pos]:9; int res = 0; for(int i = 0; i <= up; i ++){ res + = dfs(pos-1、cnt +(i == 1?1:0)、limit && i == up); } if(!limit)dp [pos] [cnt] = res; 解像度を返す。 }