重囗另类BBWSeⅹHD,av狼论坛,精品一卡2卡三卡4卡乱码理论,体育生gv老师浪小辉3p警察

LeetCode Perfect Squares -電腦資料

電腦資料 時間:2019-01-01 我要投稿
【www.ipr-jzsc.com - 電腦資料】

    題目描述

    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.

    思路:

    本題還是BFS, 遞歸的對象是完全平方數集合,以及要尋找的數集list[0...i](=n-table[0...i])

    1. 找出小于目標數:n的完全平方數,如果找到直接返回

    2. 進行BFS(完全平方數集合:table,要尋找的數集:list,層數:depth):

    循環table,針對每個小于當前n的完全平方數,求出它要尋找的數集:x={n-table[i]} , i∈[0,table.Count] => 得到list

    實現代碼

   

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(); j="0;j" pre="" var=""></p></target[i]).tolist();></int></int></int></int></int>

最新文章
主站蜘蛛池模板: 弋阳县| 贵南县| 和田县| 永嘉县| 康定县| 陵水| 丰城市| 枝江市| 宽城| 房产| 伽师县| 霍城县| 金昌市| 曲水县| 定边县| 南丹县| 保靖县| 登封市| 临安市| 灵石县| 疏附县| 靖西县| 彰武县| 台湾省| 山阳县| 蕉岭县| 新昌县| 新竹市| 顺昌县| 兰坪| 确山县| 镇江市| 峨边| 随州市| 纳雍县| 涡阳县| 沙洋县| 布尔津县| 白朗县| 铅山县| 镇远县|