Leetcode--Perfect Squares

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.