LeetCode 279. Perfect Squares
Question:
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
.
Code:
public class Solution { public int numSquares(int n) { Queue<Map.Entry<Integer, Integer>> queue = new LinkedList<>(); queue.add(new java.util.AbstractMap.SimpleEntry<Integer, Integer>(n, 0)); boolean[] visited = new boolean[n+1]; visited[n] = true; while (!queue.isEmpty()){ Map.Entry<Integer, Integer> entry = queue.poll(); int num = entry.getKey(); int step = entry.getValue(); for (int i = 1; ; i++) { int a = num - i*i; if(a < 0){ break; } if(a == 0){ return step + 1; } if (!visited[a]){ queue.add(new java.util.AbstractMap.SimpleEntry<Integer, Integer>(a, step + 1)); visited[a] = true; } } } return 0; } }
动态规划
class Solution { private boolean isSquares(int n){ int temp = (int)Math.sqrt(n); return temp*temp == n ? true:false; } public int numSquares(int n){ if(isSquares(n)){ return 1;//如果是平方数,直接返回1 } int[] dp = new int[n+1]; for(int i = 0; i < dp.length; i++){ if(isSquares(i)){ dp[i] = 1; }else{ dp[i] = Integer.MAX_VALUE; } } for (int i = 2; i < n + 1; i++) { for (int j = 1; j*j < i; j++) { dp[i] = Math.min(dp[i], dp[j*j]+dp[i-j*j]); } } return dp[n]; } }