2020-09-26 刷题记录

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\)

构造方法如下:

image-20200926134306266

代码:

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;
}
posted @ 2020-09-27 00:33  nonameless  阅读(66)  评论(0编辑  收藏  举报