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;
    }
};
posted @ 2020-03-11 17:02  鱼与鱼  阅读(94)  评论(0编辑  收藏  举报