Fibonacci数列
题目链接:Fibonacci数列_牛客题霸_牛客网 (nowcoder.com)
思路:数据范围比较水,n < 1百万 直接数组预处理 前40项斐波那契数 再进行比较 取两相邻元素与n差值的最小值即可。
AC code:
#include<iostream>
#include<cmath>
using namespace std;
const int N = 40;
int a[N] = {0,1};
int n;
int main()
{
cin >> n;
for(int i = 2; i <= 39; i ++)
a[i] = a[i - 1] + a[i - 2];
int i = 0;
for(i = 0; i <= 39; i ++)
if(n < a[i])
break;
cout << min(abs(a[i] - n), abs(a[i - 1] - n)) << endl;
return 0;
}
NC242 单词搜索
题目链接:单词搜索_牛客题霸_牛客网 (nowcoder.com)
思路:遍历数组 如果数组元素==word开头元素 进行深搜 模板题目。
AC code:
#include <string>
class Solution {
public:
bool exist(vector<string>& board, string word)
{
int m=board.size();
if(m<= 0) return false;
int n=board[0].size();
for(int i=0;i<m;i++){
for(int j=0;j<n;j++){
if (dfs(0,board,word,i,j)) {
return true;
}
}
}
return false;
}
bool dfs(int cur,vector<string>& board, string word,int i,int j)
{
if (cur==word.length()) return true;
if (i>=0&&i<board.size()&&j>=0&&j<=board[0].size()&&board[i][j]==word[cur]) {
char temp=board[i][j];
board[i][j]=0;
if(dfs(cur+1,board,word,i-1,j)) return true;
if(dfs(cur+1,board,word,i,j+1)) return true;
if(dfs(cur+1,board,word,i+1,j)) return true;
if(dfs(cur+1,board,word,i,j-1)) return true;
board[i][j]=temp;
}
return false;
}
};
BC140 杨辉三角
题目链接:杨辉三角_牛客题霸_牛客网 (nowcoder.com)
思路:每个元素 等于它上一行上一列的元素 与 上一行同一列元素 的和,为了防止越界直接用(1,1) 作为第一个元素,预先将(0,0)设为一即可。
AC code:
#include <iostream>
#include<iomanip>
using namespace std;
const int N = 1010;
int a[N][N];
int n;
int main()
{
cin >> n;
a[0][0] = 1;
for(int i = 1; i <= n ;i ++)
for(int j = 1; j <= i; j ++)
a[i][j] = a[i - 1][j] + a[i - 1][j - 1];
for(int i = 1; i <= n ;i ++)
{
for(int j = 1; j <= i; j ++)
cout << setw(5) << a[i][j];
cout << endl;
}
}