Update README.md

master
pjekuohcp 2 years ago
parent 7178e69620
commit 7616a06623

@ -1,3 +1,5 @@
### 01背包问题的递归版的精简版
~~~c
#include<stdio.h>
#define max(x,y)((x)>(y)?(x):(y))
@ -37,4 +39,123 @@ int main(){
printf("\n");
printf("总价值=%d",maxv);
}
~~~
~~~
### 斐波那契数列递归
~~~c
#include<stdio.h>
int fib(int n){
if(n<=2){
return n;
}else{
return fib(n-1)+fib(n-2);
}
}
int main(){
int n;
printf("请输入想打印的斐波拉契数列:\n");
scanf("%d",&n);
printf("斐波那契数列:\n");
for(int i = 0;i<=n;i++){
printf("%d ",fib(i));
}
return 0;
}
~~~
### 常规的求解众数和重数
~~~c
#include<stdio.h>
typedef struct{
int number;
int count;
} Mode;
Mode findMode(int arr[],int n){
Mode mode = {arr[0],1};
int count = 1;
int maxCount = 1;
for(int i=0;i<n;i++){
if(arr[i] == arr[i-1]){
count++;
}else{
if(count>maxCount){
mode.number = arr[i-1];
mode.count = count;
maxCount = count;
}
count = 1;
}
}
if(count>maxCount){
mode.number = arr[n-1];
mode.count = count;
}
return mode;
}
int main(){
int arr[] = {1,2,2,2,3,3,5,6,6,6,6};
int n = sizeof(arr)/sizeof(arr[0]);
printf("递增序列: ");
for (int i = 0; i < n; i++)//
printf("%d ",arr[i]);
printf("\n");
Mode result = findMode(arr,n);
printf("众数为:%d,重数为:%d",result.number,result.count);
return 0;
}
~~~
### 二叉树递归版
~~~c
#include<stdio.h>
#include<stdlib.h>
#define max(a,b)((a)>(b)?(a):(b))
typedef struct TreeNode{
int val;
struct TreeNode *left;
struct TreeNode *right;
}TreeNode;
int maxPathHelper(TreeNode *root,int *maxSum){
if(root==NULL){
return 0;
}
int leftSum = maxPathHelper(root->left,maxSum);
int rightSum = maxPathHelper(root->right,maxSum);
int currSum = max(max(root->val,root->val+leftSum+rightSum),
max(root->val+leftSum,root->val+rightSum));
*maxSum = max(*maxSum,currSum);
return max(root->val,max(root->val+rightSum,root->val+leftSum));
}
int maxPathSum(TreeNode *root){
if(root==NULL){
return 0;
}
int maxSum = 0;
maxPathHelper(root,&maxSum);
return maxSum;
}
TreeNode* createTreeNode(int val){
TreeNode* newNode = (TreeNode*)malloc(sizeof(TreeNode));
newNode->val=val;
newNode->left=NULL;
newNode->right=NULL;
return newNode;
}
int main(){
TreeNode* root = createTreeNode(-10);
root->left=createTreeNode(9);
root->right=createTreeNode(20);
root->right->left=createTreeNode(15);
root->right->right=createTreeNode(7);
int maxSum = maxPathSum(root);
printf("最大的路径和为:%d",maxSum);
free(root->left);
free(root->right);
free(root);
return 0;
}
~~~

Loading…
Cancel
Save