Title Description
Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, ...) which sum to n .
For example, given n = A, return 3 because 12 = 4 + 4 + 4; Given n = 13, return 2 because = 4 + 9.
Credits:
Special thanks to @jianchao. Li.fighter for adding the problem and creating all test cases.
Ideas:
In the subject or BFS, the recursive object is the complete square number set, and the number set to be searched LIST[0...I] (=n-table[0...i])
1. Find out the total squared number less than the target number: N, if you find a direct return
2. BFS (Full squared set: table, number of sets to look for: list, number of floors: depth):
Loop table, for each complete square number less than the current N, find the set of numbers it is looking for: 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<int> (); for (var i = 1;i <= len; i++) {var x = i * i;if (x = = N) {ret Urn 1;} if (x < n) {table. ADD (x);}} var list = new list<int> (); 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<int> table, ilist<int> 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<int> (); for (var i = 0;i < target. Count; i++) {var t = table. Where (X=>x<target[i]). ToList (); for (var j = 0;j < T.count; J + +) {list. ADD (Target[i]-t[j]);}} Bfs (table, list, depth+1);}}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Leetcode--Perfect Squares