LeetCode -- Perfect Squares
Description
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.
Credits:
Special thanks to @ jianchao. li. fighter for adding this problem and creating all test cases.
Ideas:
This is still BFS. The recursive object is a set of complete values and the list of number sets to be searched [0... I] (= n-table [0... I]).
1. Find the total number of workers smaller than the target number: n.
2. Perform BFS (Set of full partitions: table, number set to be searched: list, number of layers: depth ):
For a cyclic table, find the number set to be searched for each number of complete partitions less than the current n: x = {n-table [I]}, iε [0, table. count] => get list
Implementation Code
public class Solution { public int NumSquares(int n) { if(n == 1){return 1;}var len = n/2;var depth = 1;var table = new List
();for(var i = 1;i <= len; i++){var x = i * i;if(x == n){return 1;}if(x < n){table.Add(x);}}var list = new List
();for(var i = 0 ;i < table.Count; i++){list.Add(n-table[i]);}Bfs(table, list, depth + 1);return Depth;}private int Depth;private bool Found = false;public void Bfs(IList
table , IList
target , int depth){if(Found){return;}for(var i =0 ;i < table.Count; i++){for(var j = 0;j < target.Count; j++){if(table[i] == target[j]){Depth = depth;Found = true;return;}}}var list = new List
();for(var i = 0;i < target.Count; i++){var t = table.Where(x=>x