首页 > 其他 > 详细

2020-09-26 刷题记录

时间:2020-09-27 08:30:04      阅读:36      评论:0      收藏:0      [点我收藏+]

113. 路径总和 II

思路:

\(dfs\)

代码:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    
    int Sum;
    vector<vector<int>> res;
    vector<int> vec;
    
    inline void dfs(TreeNode * node, int tmpSum, vector<int> vec){
        
        cout << tmpSum << endl;
        if(node->left == NULL && node->right == NULL){
            if(tmpSum == Sum){
                res.push_back(vec);
            }
            return;
        }
        
        if(node->left){
            tmpSum += node->left->val;
            vec.push_back(node->left->val);
            dfs(node->left, tmpSum, vec);
            tmpSum -= node->left->val;
            vec.pop_back();
        }
        if(node->right){
            tmpSum += node->right->val;
            vec.push_back(node->right->val);
            dfs(node->right, tmpSum, vec);
            tmpSum -= node->right->val;
            vec.pop_back();
        }
        
    }
    
    vector<vector<int>> pathSum(TreeNode* root, int sum) {
        
        if(root == NULL) return res; 
        Sum = sum - root->val;
        vec.push_back(root->val);
        dfs(root, 0, vec);
        return res;
        
        
    }
};

Grid-00100

思路:

构造。

判断 \(k \% n == 0?\)

\(if(k\ \%\ n = 0):\) \(f(A) = 0\)

\(if(k\ \%\ n \ne 0):\) \(f(A) = 2\)

构造方法如下:

技术分享图片

代码:

const int N = 310;

int a[N][N];

int main(){

    int t; cin >> t;
    while(t --){
        memset(a, 0, sizeof a);
        int n, k; cin >> n >> k;
        int cnt1 = k / n, cnt2 = k % n;
        for(int i = 0; i < n; i ++){
            int mx = i < cnt2 ? cnt1 + 1 : cnt1;
            for(int j = i; j < i + mx; j ++)
                a[i][j % n] = 1;
        }
        if(cnt2 == 0) puts("0");
        else puts("2");
        for(int i = 0; i < n; i ++){
            for(int j = 0; j < n; j ++) cout << a[i][j];
            puts("");
        }
    }
    return 0;
}

2020-09-26 刷题记录

原文:https://www.cnblogs.com/nonameless/p/13737449.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!