给定正整数 n,找到若干个完全平方数(比如 1, 4, 9, 16, ...)使得它们的和等于 n。你需要让组成和的完全平方数的个数最少。
示例 1:
输入: n = 12
输出: 3
解释: 12 = 4 + 4 + 4.
示例 2:
输入: n = 13
输出: 2
解释: 13 = 4 + 9.
方法1:深度优先(BFS)
1 public class T279 { 2 public int numSquares(int n) { 3 List<Integer> squareList = getSquareArray(n); 4 Queue<Integer> que = new LinkedList<>(); 5 que.add(n); 6 boolean[] visited = new boolean[n]; 7 int level = 0; 8 while (!que.isEmpty()) { 9 int size = que.size(); 10 level++; 11 while (size-- > 0) { 12 int num = que.poll(); 13 for (int square : squareList) { 14 int left = num - square; 15 if (left == 0) { 16 return level; 17 } 18 if (left < 0) { 19 break; 20 } 21 if (visited[left]) { 22 continue; 23 } 24 visited[left] = true; 25 que.add(left); 26 } 27 28 } 29 } 30 return level; 31 } 32 33 private ArrayList<Integer> getSquareArray(int n) { 34 ArrayList<Integer> list = new ArrayList<>(); 35 for (int i = 1; i <= n; i++) { 36 int num = i * i; 37 if (num <= n) { 38 list.add(num); 39 } else { 40 break; 41 } 42 } 43 return list; 44 } 45 }
方法二:dp
1 public class T279 { 2 public int numSquares(int n) { 3 List<Integer> squareList = getSquareArray(n); 4 int[] dp = new int[n + 1]; 5 for (int i = 1; i <= n; i++) { 6 int min = Integer.MAX_VALUE; 7 for (int num : squareList) { 8 if (num <= i) { 9 min = Math.min(dp[i - num] + 1, min); 10 } 11 } 12 dp[i] = min; 13 } 14 return dp[n]; 15 } 16 17 private ArrayList<Integer> getSquareArray(int n) { 18 ArrayList<Integer> list = new ArrayList<>(); 19 for (int i = 1; i <= n; i++) { 20 int num = i * i; 21 if (num <= n) { 22 list.add(num); 23 } else { 24 break; 25 } 26 } 27 return list; 28 } 29 }