ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

PO88前两数之和

2021-09-15 05:02:09  阅读:17  来源: 互联网

标签:index curr int list num length PO88 两数


image

思路:回溯+剪枝

#include<vector>
#include<string>
#include<limits.h> 

using namespace std;

class Solution {
public:
    bool backtrack(vector<int>& list, string num, int length, int index, long long sum, int prev) {
        if (index == length) {
            return list.size() >= 3;
        }
        long long curr = 0;
        for (int i = index; i < length; i++) {
            if (i > index && num[index] == '0') {
                break;
            }
            curr = curr * 10 + num[i] - '0';
            if (curr > INT_MAX) {
                break;
            }
            if (list.size() >= 2) {
                if (curr < sum) {
                    continue;
                }
                else if (curr > sum) {
                    break;
                }
            }
            list.push_back(curr);
            if (backtrack(list, num, length, i + 1, prev + curr, curr)) {
                return true;
            }
            list.pop_back();
        }
        return false;
    }
};
int main(){
    Solution solution;
    string str;
    cin>>str;
    vector<int>list;
    if(solution.backtrack(list, str, str.length(), 0, 0, 0)){
        cout<<"true"<<endl;
    }else{
        cout<<"false"<<endl;
    }
    return 0;
}

-[1]842. 将数组拆分成斐波那契序列

标签:index,curr,int,list,num,length,PO88,两数
来源: https://www.cnblogs.com/aoke2002/p/15270531.html

专注分享技术,共同学习,共同进步。侵权联系[admin#icode9.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有