LeetCode 279. Perfect Squares
Posted Realvie
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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的主要内容,如果未能解决你的问题,请参考以下文章
[LeetCode] 279. Perfect Squares