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

首頁 > 學院 > 開發設計 > 正文

LeetCode Jump Game II

2019-11-11 06:16:12
字體:
來源:轉載
供稿:網友

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.

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

代碼如下:

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;        }};結果是用時超時,需要進行剪枝或尋找更好的方法

思路二:仔細分析題目發現,題目關心的是最少通過幾步達到,對于具體的到達選擇并不關心,并且必然會達到。所以可以將其轉換為廣度優先算法模型,然后采用貪心原則進行求解,

代碼如下:

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;    }};


上一篇:ASP.NET Cache緩存

下一篇:qt protobuf使用

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 平山县| 黔东| 凉城县| 巫山县| 达州市| 陇西县| 泗水县| 芒康县| 务川| 大渡口区| 达州市| 湘潭县| 徐闻县| 班戈县| 古丈县| 大同县| 镇安县| 腾冲县| 黄大仙区| 岗巴县| 文成县| 和田市| 丰镇市| 龙南县| 嘉定区| 临清市| 饶平县| 潞西市| 旬阳县| 西乌珠穆沁旗| 阿拉善盟| 荆州市| 盐城市| 敖汉旗| 连南| 新宁县| 达日县| 辽阳市| 淳安县| 顺昌县| 灌南县|