Topic:
Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...
) which sum to n.
For example, given n = 12
, return 3
because 12 = 4 + 4 + 4
; given n = 13
, return 2
because 13 = 4 + 9
.
Links: http://leetcode.com/problems/perfect-squares/
Exercises
is a math problem, every time a look at Jianchao.li.fighter added to the topic, you know with the number of relations. Math is not good for me, do it really big head .... This problem saw discuss later found that there are many methods, there are DP, BFS, and pure mathematical solution. Here is the simplest DP, the core of the recursive formula for j= 1, J * J <= I, TMP = Math.min (tmp, TMP[I-J * j] + 1);
Time Complexity-o (NLOGN), Space complexity-o (n)
Public classSolution { Public intNumsquares (intN) {if(N < 1) { return0; } int[] min =New int[n + 1]; for(inti = 1; I <= N; i++) { intTMP =Integer.max_value; for(intj = 1; J * J <= I; J + +) {tmp= Math.min (tmp, MIN[I-J * j] + 1); } Min[i]=tmp; } returnMin[n]; }}
Off Topic:
Recently seems to lose the ability to think independently, every time I think about 5 minutes to be impatient to see the discuss answer. This does not work, the need to exercise is not to memorize problems, but their own thinking. It's really lazy to get home.
Reference:
Https://leetcode.com/discuss/58056/summary-of-different-solutions-bfs-static-and-mathematics
Https://leetcode.com/discuss/56982/o-sqrt-n-in-ruby-c-c
Https://leetcode.com/discuss/62526/an-easy-understanding-dp-solution-in-java
Https://leetcode.com/discuss/56983/simple-java-dp-solution
Https://leetcode.com/discuss/57021/simple-java-solution
Https://leetcode.com/discuss/57850/explanation-of-the-dp-solution
Https://leetcode.com/discuss/68295/beautiful-9-lines-java-solution
Https://leetcode.com/discuss/57020/java-solution-o-n-1-2-time-and-o-1-space
Https://leetcode.com/discuss/57477/sqrt-applying-fermats-theorm-brahmagupta-fibonacci-identity
Https://leetcode.com/discuss/63750/concise-java-dp-solution
Https://en.wikipedia.org/wiki/Fermat%27s_theorem_on_sums_of_two_squares
279. Perfect Squares