标签:
题目描述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){
return 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);
}
}版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:
原文地址:http://blog.csdn.net/lan_liang/article/details/48576005