首页 > 代码库 > LeetCode 279. Perfect Squares
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; } }
看到其他网友提交的代码,有用动态规划的,感觉比自己写的思路简单的多,也贴出来学习
public class Solution { public int numSquares(int n) { if (n < 2) return 1; int[] dp = new int[n+1]; for (int i = 1; i <= n; i ++) { int val = Integer.MAX_VALUE; for (int j = 1; j * j <= i; j ++) { val = Math.min(val, dp[i-j*j]); } dp[i] = val + 1; } return dp[n]; } }
LeetCode 279. Perfect Squares
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。