LeetCode 679. 24 点游戏

题目链接:

https://leetcode-cn.com/problems/24-game/

思路:非常经典的暴搜题。虽然没有什么算法,但却是练习dfs的好机会。

本质就是不断从数组中取出两个数,进行加减乘除运算,然后将新值在放入数组中。

剪枝有两个方向,第一当找到能得到24的组合时,结束递归。

第二,加法和乘法有交换性。

class Solution {
public:
    double eps = 1e-5;
    bool ans=0;
    bool judgePoint24(vector& nums) {
        vector vec;
        for(auto t:nums) vec.push_back(t);
        dfs(vec);
        //cout< vec)
    {
        //cout<=(24-eps)) ans=1;
            return;
        }
        for(int i=0;ii) continue;
                    double tmp;
                    bool flag=0;
                    if(k==0)
                    {
                        tmp = (a+b);
                    }
                    else if(k==1)
                    {
                        tmp = (a-b);
                    }
                    else if(k==2)
                    {
                        tmp=a*b;
                    }
                    else
                    {
                        if(fabs(b) dl;
                    for(int t=0;t

 

你可能感兴趣的:(LeetCode)