發表文章

目前顯示的是有「演算法」標籤的文章

LeetCode第633題_Sum of Square Numbers

圖片
Given a non-negative integer  c , your task is to decide whether there're two integers  a  and  b  such that a 2  + b 2  = c. Example 1: Input: 5 Output: True Explanation: 1 * 1 + 2 * 2 = 5 Example 2: Input: 3 Output: False 題目就是給定一個數輸入 判定是不是某兩個數的平方和 就是如此 1 -> 0^2 + 1^2 =1 -> true 2-> 1^2 + 1^2 = 2 -> true ... 3 -> x 4-> 0^2+2^2 = 4  ->true 第一版.直觀法(暴力法) 使用兩層迴圈去跑 範圍皆從0跑到該數 利用演算法【奇數之平方和必為一可開平方數】 圖像理解(正方形的邊) 所以改寫至程式進行算法優化後 原本輸入9 我的作法是給其跑兩層迴圈 i從0到9 j從0到9 ------------------------------- i=0時 j=0,j=1,j=2.......j=9給個都去跑 . . . i=9時 j=0,j=1,j=2.......j=9 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the edito...

LeetCode第50題_Pow(x, n)_Divide & Conquer

圖片
題目 Implement  pow( x ,  n ) , which calculates  x  raised to the power  n  (x n ). Example 1: Input: 2.00000, 10 Output: 1024.00000 Example 2: Input: 2.10000, 3 Output: 9.26100 Example 3: Input: 2.00000, -2 Output: 0.25000 Explanation: 2 -2 = 1/2 2 = 1/4 = 0.25 Note: -100.0 <  x  < 100.0 n  is a 32-bit signed integer, within the range [−2 31 , 2 31  − 1] 需要考量的問題: 1.輸入的指數正負性 2.指數為奇為偶的情況 較直觀且簡易的一般作法 是直接跑Loop 當次方為1時代表保持不變回傳原本輸入的數值 其餘狀況 則判定指數n是否>1 是 ,則依序做n次累乘 否 ,則做累除 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package leetcode50_pow ; import java.io.Buffered...

貪婪法_找零錢問題

貪婪法 (Greedy Algorithm) 貪心演算法 尋找問題最優解之方法 一般會將問題求解過程分割成若干個步驟(對問題進行拆解) 並在每個步驟都應用Greedy原則 選擇目前狀態下最好or最優的選擇(選擇傾向於局部最有利的概念) Step1. 建立數學模型(最優解模型) Step2. 問題分解一系列子問題 並同時定義子問題最優解 Step3. 應用貪心原則確定每個子問題之局部最優解            根據最優解模型,將子問題的局部最優解堆疊出全域最優解 某國發行的貨幣 總共有 25分 、 10分 、 5分、1分 四種貨幣 假設你是銷售員 要找給客戶41分錢 硬幣 要如何安排才可使找給客人的錢正確且硬幣個數最少 這個經典問題的子問題定義 即是  從  四種 幣值的硬幣中選擇一枚 使它和其他已經選擇的硬幣幣值總額不超過  41分錢 使用貪婪策略進行下 【以幣值總額不超過41為前提,我們優先選擇幣值大者進行擺放】 我們會選擇   最大幣值去 step1.  25 step2.  10 step3.  5 step4.  1 total:41 ---> 總共 四個硬幣 此為本問題之   最優解 無最優解的情況探討 某國發行的貨幣 總共有 25分 、 20分 、 5分、1分 四種貨幣 這時最優策略 2個 20分    1  個  1分 總共     3個硬幣 用貪婪得到的則是 1個25分    3  個  5分    1個 1分 總共    5個硬幣