zoukankan      html  css  js  c++  java
  • LeetCode-0311

    322.零钱兑换

    class Solution:
        def coinChange(self, coins: List[int], amount: int) -> int:
            dp = [float('inf')]*(amount+1)
            dp[0] = 0
            for coin in coins:
                for x in range(coin,amount+1):
                    dp[x] = min(dp[x],dp[x-coin]+1)
            return dp[amount] if dp[amount]!=float('inf') else -1
    

    1013.将数组分成和相等的三个部分

    python

    # 求和 除以 3 遍历
    class Solution:
        def canThreePartsEqualSum(self, A: List[int]) -> bool:
            if sum(A)%3 != 0:
                return False
            count = 0 #定义和为3子数组个数,等于3则满足要求
            ans = sum(A)//3
            subsum = 0
            for i in range(len(A)):
                subsum +=A[i]
                if subsum == ans:
                    count += 1
                    subsum = 0
                if count == 3:
                    return True
            return False
    
    #双指针解法
    # 从头尾开始遍历,如何和等于sum/3,中间部分一定也为3
    class Solution:
        def canThreePartsEqualSum(self, A: List[int]) -> bool:
            if sum(A)%3 != 0:
                return False
            ans = sum(A)//3
            left,right = 0,len(A)-1
            leftsum,rightsum =A[left],A[right]
            while left+1 < right:
                if leftsum==ans and rightsum ==ans:
                    return True
                if leftsum != ans:
                    left += 1
                if rightsum != ans:
                    right -= 1
            return False
    

    c++

    class Solution {
    public:
        bool canThreePartsEqualSum(vector<int>& A) {
            int sum = accumulate(A.begin(), A.end(), 0);
            if(sum%3!=0){
                return false;
            }
            int count = 0,ans = sum/3,subsum = 0;
            for(int i=0;i<A.size();i++){
                subsum += A[i];
                if (subsum==ans){
                    count+=1;
                    subsum = 0;
                    }
                if (count==3){
                    return true;
                }
            }
            return false;
        }
    };
    
  • 相关阅读:
    go相关
    mac下使用vscode技巧
    mac下secureCRT的使用技巧
    python subprocess实时输出
    python中多级目录导入模块问题
    python的print与sys.stdout
    python中类相关笔记
    python中sys.stdout.flush()的作用
    nginx+uwsgi配置
    虚拟机的 基本配置
  • 原文地址:https://www.cnblogs.com/gongyanzh/p/12463539.html
Copyright © 2011-2022 走看看