LeetCode:动态规划+贪心题目整理

这篇博客整理了多个使用动态规划和贪心算法解题的LeetCode题目,包括字符串分割、分糖果、加油站、三角形最小路径和等,通过AC代码展示了如何应用这两种算法解决问题。
摘要由CSDN通过智能技术生成

     以下均为AC代码,后续将不断更新……

 

1.字符串分割:(LeetCode:word-break)

 

        Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words.

        For example, given  s ="leetcode",    dict =["leet", "code"]. Return true because"leetcode"can be segmented as"leet code".

        题意:判断字符串能够分割为有集合中的几个词汇组成。

        题解: 动态规划,状态visited(i):表示以i结尾的是否能够满足条件,每次对从0-i的字符进行判断。

import java.util.*;
public class Solution {
    public boolean wordBreak(String s, Set<String> dict) {
        char [] list = s.toCharArray();
        boolean [] visited = new boolean[list.length+1];
        visited[0] = true;
        for(int i =1;i<=list.length;i++){
            for(int j = 0 ;j< i;j++){
                if(visited[j] && dict.contains(s.substring(j,i))){
                    visited[i] = true;
                    break;
                }
            }
        }
     return visited[list.length];
    }
}

 

2.字符串分割II(LeetCode:word-break-ii)

        Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each word is a valid dictionary word.Return all such possible sentences.

         For example, given   s ="catsanddog",     dict =["cat", "cats", "and", "sand", "dog"]. A solution is["cats and dog", "cat sand dog"].

        题意:字符串分割后组成的句子的所有组合。

        题解:使用DFS,从头部开始会超时,因此,从尾部开始,进行DFS,最后添加时去掉尾部的空格。

import java.util.*;
public class Solution {
    ArrayList<String> result = new ArrayList<String>(); 
     public void dfs(String s,int index, Set<String> dict,String cur) {
        if(index<=0){
            if(cur.length()>0)
                result.add(cur.substring(0,cur.length()-1));
        }
        for(int i = index;i>=0;i--){
            if(dict.contains(s.substring(i,index))){
                dfs(s,i,dict,s.substring(i,index)+" "+cur);
            }
        }
    }

    public ArrayList<String> wordBreak(String s, Set<String> dict) {
        dfs(s,s.length(),dict,"");
        return result;
    }
}

 

3.分糖果(LeetCode:candy):

      There are N children standing in a line. Each child is assigned a rating value.You are giving candies to these children subjected to the following requirements:

  • Each child must have at least one candy.
  • Children with a higher rating get more candies than their neighbors.

      What is the minimum candies you must give?

      题意:每个小朋友都有一颗糖,节点高的同学比旁边的孩子多拿糖,求最少的糖个数。

       题解:遍历两边,首先每个人得一块糖,第一遍从左到右,若当前点比前一个点高就比前者多一块。 这样保证了在一个方向上满足了要求。第二遍从右往左,若左右两点,左侧高于右侧,但左侧的糖果数不多于右侧,则左侧糖果数等于右侧糖果数+1,这就保证了另一个方向上满足要求

public class Solution {
    public int candy(int[] ratings) {
        int dp[] = new int[ratings.length];
        if(ratings.length==1)
            return 1;
        for(int i =0;i<ratings.length;i++){
            dp[i]= 1;
        }
        for(int i =1;i<ratings.length;i++){
            if(ratings[i]>ratings[i-1]  )
                dp[i]= dp[i-1]+1;
        }
        int count =dp[ratings.length-1];
        for(int i =ratings.length-2;i>=0;i--){
            if(ratings[i]>ratings[i+1] && dp[i]<=dp[i+1] )
                dp[i]= dp[i+1]+1;
            count+=dp[i];
        }
        return count;
    }
}

 

4.加油站(LeetCode:gas-station)

    There are N gas stations along a circular route, where the amount of gas at station i isgas[i]. You have a car with an unlimited gas tank and it costscost[i]of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one of the gas stations. Return the starting gas station's index if you can travel around the circuit once, otherwise return -1.

Note:
      The solution is guaranteed to be unique.

       题意:环形路线上有N个加油站,每个加油站有汽油gas[i],从每个加油站到下一站消耗汽油cost[i],问从哪个加油站出发能够回到起始点,如果都不能则返回-1(注意,解是唯一的)。

        题解:total用来判断是否有解,total<0表示没有解,同理,从i点出发,如果remains<0,表示无法到达该点,应该从下一个点开始重新计算,因为第一个点开始时remains>0,当小于0时,中间的点也无法到达该点。

public class Solution {
    public int canCompleteCircuit(int[] gas, int[] cost) {
        int index = -1;
        int total =0;
        int dif =0;
        int remains = 0;
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值