笔试强训day04


Fibonacci数列

#include 
using namespace std;
int n;
int main() {
    cin >> n;
    int a = 0, b = 1, c = 1;
    while (n > c) {
        a = b;
        b = c;
        c = a + b;
    }
    cout << min(c - n, n - b) << endl;
    return 0;
}


单词搜索

#include 
#include 
class Solution {
private:
    int n,m;
    int dx[4] = {1,-1,0,0},dy[4] = {0,0,1,-1};
    bool vis[110][110]{};
    bool dfs(int i,int j,int u,const string &s,vector<string>&board)
    {
        if(u == s.size()-1)return true;
        vis[i][j] = true;
        for(int k = 0;k<4;++k)
        {
            int x = i+dx[k],y = j+dy[k];
            if(x>=0&&x<n&&y>=0&&y<m&&!vis[x][y]&&board[x][y] == s[u+1])
                if(dfs(x,y,u+1,s,board))return true;
        }
        vis[i][j] = false;
        return false;
    }
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param board string字符串vector 
     * @param word string字符串 
     * @return bool布尔型
     */
    bool exist(vector<string>& board, string word) {
        // write code here
        n = board.size(),m = board[0].size();
        for(int i = 0;i<n;++i)
        {
            for(int j = 0;j<m;++j)
            {
                if(board[i][j] == word[0]&&dfs(i,j,0,word,board))return true;
            }
        }
        return false;
    }
};


杨辉三角

#include 
#include 

using namespace std;
int n;
const int N = 40;
int dp[N][N];

int main()
{
    scanf("%d",&n);
    dp[1][1] = 1;
    for(int i = 2;i<=n;++i)
    {
        for(int j = 1;j<=i;++j)
        {
            dp[i][j] = dp[i-1][j]+dp[i-1][j-1];
        }
    }
    for(int i = 1;i<=n;++i)
    {
        for(int j = 1;j<=i;++j)
        {
            printf("%5d",dp[i][j]);
        }
        printf("\n");
    }
    return 0;
}

你可能感兴趣的:(笔试强训,算法,图论,深度优先)