Perfect Squares Solutions in Java
Number 279
Difficulty Medium
Acceptance 47.5%
Link LeetCode
Other languages C++
Solutions
Java solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/perfect-squares/description//// Author : liuyubobobo/// Time : 2017-11-17import java.util.LinkedList;import javafx.util.Pair;/// BFS/// Time Complexity: O(n)/// Space Complexity: O(n)public class Solution1 {public int numSquares(int n) {if(n == 0)return 0;LinkedList<Pair<Integer, Integer>> queue = new LinkedList<Pair<Integer, Integer>>();queue.addLast(new Pair<Integer, Integer>(n, 0));boolean[] visited = new boolean[n+1];visited[n] = true;while(!queue.isEmpty()){Pair<Integer, Integer> front = queue.removeFirst();int num = front.getKey();int step = front.getValue();if(num == 0)return step;for(int i = 1 ; num - i*i >= 0 ; i ++){int a = num - i*i;if(!visited[a]){if(a == 0) return step + 1;queue.addLast(new Pair(num - i * i, step + 1));visited[num - i * i] = true;}}}throw new IllegalStateException("No Solution.");}public static void main(String[] args) {System.out.println((new Solution1()).numSquares(12));System.out.println((new Solution1()).numSquares(13));}}
Java solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/perfect-squares/description//// Author : liuyubobobo/// Time : 2017-11-17import java.util.Arrays;/// Memory Search/// Time Complexity: O(n)/// Space Complexity: O(n)public class Solution2 {public int numSquares(int n) {int[] mem = new int[n+1];Arrays.fill(mem, -1);return numSquares(n, mem);}private int numSquares(int n, int[] mem){if(n == 0)return 0;if(mem[n] != -1)return mem[n];int res = Integer.MAX_VALUE;for(int i = 1; n - i * i >= 0; i ++ )res = Math.min(res, 1 + numSquares(n - i * i, mem));return mem[n] = res;}public static void main(String[] args) {System.out.println((new Solution2()).numSquares(12));System.out.println((new Solution2()).numSquares(13));}}
Java solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/perfect-squares/description//// Author : liuyubobobo/// Time : 2017-11-17import java.util.Arrays;/// Dynamic Programming/// Time Complexity: O(n)/// Space Complexity: O(n)public class Solution3 {public int numSquares(int n) {int[] mem = new int[n+1];Arrays.fill(mem, Integer.MAX_VALUE);mem[0] = 0;for(int i = 1; i <= n ; i ++)for(int j = 1 ; i - j * j >= 0 ; j ++)mem[i] = Math.min(mem[i], 1 + mem[i - j * j]);return mem[n];}public static void main(String[] args) {System.out.println((new Solution3()).numSquares(12));System.out.println((new Solution3()).numSquares(13));}}