国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 學(xué)院 > 開(kāi)發(fā)設(shè)計(jì) > 正文

LeetCode Jump Game II

2019-11-11 06:12:49
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

Given an array of non-negative integers, you are initially positioned at the first index of the array.

Each element in the array rePResents your maximum jump length at that position.

Your goal is to reach the last index in the minimum number of jumps.

For example:Given array A = [2,3,1,1,4]

The minimum number of jumps to reach the last index is 2. (Jump 1 step from index 0 to 1, then 3 steps to the last index.)

Note:You can assume that you can always reach the last index.

思路一:將所有的情況都考慮進(jìn)去,基于遞歸進(jìn)行暴力搜索

代碼如下:

class Solution {public:    void oneJump(vector<int>& nums,int& minJump,int& count,int& pos)    {        if(pos == nums.size()-1)        {            if(minJump > count)            {                minJump = count;                return;            }        }                    for(int i=pos+1;i<=pos+nums[pos];i++)        {            if(i>nums.size()-1)                return;            count++;            oneJump(nums,minJump,count,i);            count--;        }    }        int jump(vector<int>& nums) {        int minJump = 0x7fffffff;        int count = 0;        int pos = 0;        oneJump(nums,minJump,count,pos);        return minJump;        }};結(jié)果是用時(shí)超時(shí),需要進(jìn)行剪枝或?qū)ふ腋玫姆椒?p>

思路二:仔細(xì)分析題目發(fā)現(xiàn),題目關(guān)心的是最少通過(guò)幾步達(dá)到,對(duì)于具體的到達(dá)選擇并不關(guān)心,并且必然會(huì)達(dá)到。所以可以將其轉(zhuǎn)換為廣度優(yōu)先算法模型,然后采用貪心原則進(jìn)行求解,

代碼如下:

class Solution {public:    int jump(vector<int>& nums) {        if(nums.size() < 2)            return 0;                    int level=0,currentMax=0,nextMax=0;        int pos=0;        while(currentMax-pos+1>0)        {            level++;            for(;pos<=currentMax;pos++)            {                if(pos+nums[pos] > nextMax)                    nextMax = pos+nums[pos];                if(nextMax >= nums.size()-1)                    return level;            }            currentMax = nextMax;        }        return 0;    }};


發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 孟州市| 古浪县| 潮安县| 长武县| 天镇县| 寿阳县| 宣恩县| 金乡县| 阿鲁科尔沁旗| 冷水江市| 曲阳县| 嘉祥县| 桐乡市| 高陵县| 江安县| 静宁县| 连城县| 安远县| 长治县| 苗栗县| 达孜县| 惠东县| 屏东市| 巧家县| 白山市| 镇原县| 英吉沙县| 萨嘎县| 江孜县| 鄢陵县| 平邑县| 惠州市| 靖安县| 鞍山市| 多伦县| 铁岭市| 南岸区| 微山县| 博爱县| 斗六市| 晋宁县|