笔试强训(四)
一.Fibonacci数列
https://www.nowcoder.com/practice/18ecd0ecf5ef4fe9ba3f17f8d00d2d66?tpId=122&tqId=33668&ru=/exam/oj
#include <iostream>
using namespace std;int main()
{int n;cin >> n;int a = 0, b = 1, c = 1;while (b < n){a = b;int t = c;c = b + c;b = t;}cout << min(abs(n - b), min(abs(n - c), abs(n - a)));return 0;
}
二. 单词搜索
https://www.nowcoder.com/practice/987f2981769048abaf6180ed63266bb2?tpId=196&tqId=39583&ru=/exam/oj
class Solution {
public:/*** 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可** * @param board string字符串vector * @param word string字符串 * @return bool布尔型*/int n;int m;int dir[4][2] = {{0,-1},{0,1},{-1,0},{1,0}};bool book[105][105] = {false};bool dfs(vector<string>& board,int x,int y, string word,int now){if(now == word.size()){return true;}book[x][y] = true;for(int i = 0;i < 4; i++){int x1 = x + dir[i][0];int y1 = y + dir[i][1];if(x1 >=0 && y1 >=0 &&x1 < n && y1 < m && !book[x1][y1] && board[x1][y1] == word[now]){if (dfs(board,x1,y1,word,now + 1)){return true;}}}book[x][y] = false;return false;}bool exist(vector<string>& board, string word) {// write code heren = 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]){if(dfs(board,i,j,word,1)){return true;}}}}return false;}
};
三. 杨辉三角
https://www.nowcoder.com/practice/e671c6a913d448318a49be87850adbcc?tpId=290&tqId=39928&ru=/exam/oj
#include <iostream>
using namespace std;int dp[31][31];int main()
{int n;cin >> 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;
}