279. Perfect Squares
Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n. Example 1: Input: n = 12 Output: 3 Explanation: 12 = 4 + 4 + 4. Example 2: Input: n = 13 Output: 2 Explanation: 13 = 4 + 9. https://leetcode.com/problems/perfect-squares/discuss/71475/Short-Python-solution-using-BFS Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n. Example 1: Input: n = 12 Output: 3 Explanation: 12 = 4 + 4 + 4. Example 2: Input: n = 13 Output: 2 Explanation: 13 = 4 + 9. Bfs class Solution{ // 1 4 9 16 public int numSquares(int n){ if(n < 4) return n; int rootN = (int) Math.sqrt(n); // why use (int) int[] squares = new int[rootN]; // fill in the squares with 1, 4, 9, 16 .. for(int i = 0; i < squares.length; i++){ squares[i] = (i + 1) * (i + 1); // 0: 1, 1: 4 , 2 : 9 } int level = 1; Queue<Integer> queue = new LinkedList<>(); queue.offer(n); while(!queue.isEmpty()){ int size = queue.size(); for(int i = 0; i < size; i++){ int cur = queue.poll(); for(int j = 0; j < squares.length; j++){ if(cur < squares[j]) break; int newVal = cur - squares[j]; if(newVal == 0) return level; if(newVal > 0) queue.offer(newVal); } } level++; } return level; } } Dp 一种更好的方法是要求dp[i] 可以用dp[i] = min( dp[i- j*j] + 1, dp[i]), 这样是把问题转换为去掉一个数的平方之后的数是由几个平方数构成. // correct 别人的代码, 不太明白 class Solution { public int numSquares(int n) { int[] dp = new int[n + 1]; Arrays.fill(dp, Integer.MAX_VALUE); dp[0] = 0; for(int i = 1; i <= n; i++){ int min = Integer.MAX_VALUE; int j = 1; while(i - j * j >= 0){ min = Math.min(min, dp[i - j * j] + 1); j++; } dp[i] = min; } return dp[n]; } }
posted on 2018-11-06 07:38 猪猪🐷 阅读(121) 评论(0) 收藏 举报
浙公网安备 33010602011771号