力扣题目汇总

文章目录

      • 1315. Sum of Nodes with Even-Valued Grandparent
    • DFS
      • 473. 火柴拼正方形
      • 494. 目标和
      • 46. Permutations
    • 北京大学 OJ:
    • 链表
      • 反转链表
      • 相交链表
      • 5. 最长回文子串

1315. Sum of Nodes with Even-Valued Grandparent

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */


int sumEvenGrandparent(struct TreeNode* root){
    return getSum(root);
}

int getSum(struct TreeNode* root) {
    int sum = 0;
    if(root==NULL) {
        return sum;
    }   
    
    struct TreeNode* left = root->left;
    struct TreeNode* right = root->right;
    
    if (root->val%2 == 0) {
        if (left != NULL) {
            struct TreeNode* left_left = left->left;
            struct TreeNode* left_right = left->right;
            if (left_left != NULL) {
                sum += left_left->val;
            }
            if (left_right != NULL) {
                sum += left_right->val;
            }
        }

        if (right != NULL) {
            struct TreeNode* right_left = right->left;
            struct TreeNode* right_right = right->right;
            if (right_left != NULL) {
                sum += right_left->val;
            }
            if (right_right != NULL) {
                sum += right_right->val;
            }
        }
    }

    
    sum += getSum(root->left) + getSum(root->right);
    
    return sum;
}


DFS

473. 火柴拼正方形

473. 火柴拼正方形

int edge_num = 0; // 已组成边的个数
int edge_len = 0; // 边的长度

bool dfs(int idx, int curr_len, int *nums, int *vis, int numsSize);

int cmpfunc (const void * a, const void * b)
{
   return ( *(int*)a - *(int*)b );
}

bool makesquare(int* nums, int numsSize){
    int i;
    int sum = 0;    
    qsort(nums, numsSize, sizeof(int), cmpfunc);

    for (i=0; i<numsSize; i ++) {
        sum += nums[i];
    }

    if (sum%4 != 0) {
        return false;
    }

    int *vis = (int *)malloc(numsSize*sizeof(int));
    memset(vis, 0, numsSize*sizeof(int));

    edge_len = sum/4;
    edge_num = 0;

    return dfs(0, 0, nums, vis, numsSize);    
}

/*
* idx: 从该索引开始搜索。
* curr_len:当前组成的长度。
* vis: 记录某个索引数值是否使用过。
* numsSize:数组大小。
*/

bool dfs(int idx, int curr_len, int *nums, int *vis, int numsSize) {
    if (edge_num == 4) {
        // 若组成边长为4, 则完成搜索。
        return true;
    }

    if (edge_num < 4) {
        for (int i=idx; i<numsSize; i ++) {
            if (vis[i] == 1) {
                continue;
            }
            if (i>0 && vis[i-1]==0 && nums[i-1]==nums[i]) {
                continue;
            }
            if (nums[i]+curr_len < edge_len) {
                vis[i] = 1;
                bool flag = dfs(i+1, nums[i]+curr_len, nums, vis, numsSize);
                if (flag == false) {
                    //将索引为i的数值加入后,其他的数据无法组成边长,则将索引为i的数值退出,进行回溯处理
                    vis[i] = 0;
                } else {
                    return true;
                }                
            }

            if (nums[i]+curr_len == edge_len) {
                vis[i] = 1;
                edge_num ++;
                bool flag = dfs(0, 0, nums, vis, numsSize);
                if (flag == true) {
                    return true;
                }
                // 回溯
                vis[i] = 0;
                edge_num --;
            }
        }
    }

    return false;
}

494. 目标和

494. 目标和

int sumways = 0;

int cmp(const void *a, const void *b) {
    return (*(int *)b) - (*(int *)a);
}


int findTargetSumWays(int* nums, int numsSize, int S){
    int i = 0;

    qsort(nums, numsSize, sizeof(int), cmp);
    int *sum = (int *)malloc(numsSize * sizeof(int));

    for (i=numsSize-1; i>=0; i --)     {
        if (i == numsSize-1) {
            sum[i] = nums[i];
            continue;
        }
        sum[i] = sum[i+1] + nums[i];
    }

    sumways = 0;

    dfs(0, 0, nums, numsSize, S, sum);

    return sumways;
}

void dfs(int idx, int curr_value, int *nums, int numsSize, int S, int *sum) {
    if (idx==numsSize-1) {
        if (curr_value+nums[idx] == S) {
            sumways ++;                        
        }
        if (curr_value-nums[idx] == S) {
            sumways ++;                        
        }
        return ;
    }

    if (idx < numsSize-1) {
        if (curr_value+nums[idx]+sum[idx+1] < S) {
            return;
        }
        if (curr_value-nums[idx]-sum[idx+1] > S) {
            return;
        }

        dfs(idx+1, curr_value+nums[idx], nums, numsSize, S, sum);
        dfs(idx+1, curr_value-nums[idx], nums, numsSize, S, sum);        
    }
    return ;
}

46. Permutations

public class Solution {
    List<List<Integer>> ls = new ArrayList<>();
    
    public List<List<Integer>> permute(int[] nums) {
        int len = nums.length;
        for(int i=0; i<len; i ++){
            add(nums[i]);
        }
        
        return ls;
    }
    
    public void add(int n){
        int size = ls.size();
        if(size==0){
            List<Integer> tls = new ArrayList<>();
            tls.add(n);
            ls.add(tls);
            return;
        }
        
        List<List<Integer>> lsls = new ArrayList<>();
        for(List<Integer> li:ls){
            for(int i=0; i<=li.size(); i ++){
                List<Integer> tls = new ArrayList<>(li);
                tls.add(i, n);
                lsls.add(tls);
            }
        }
        
        ls = lsls;
    }
}

北京大学 OJ:

1011-木棒

#include      // std::cout
#include     // std::sort
#include        // std::vector
#include 
#include 
#include 
#define Max 101
using namespace std;
int sticks[Max],vis[Max];
int min_len; // 满足条件的最小长度
int stick_num;//  木棍数量 
int n;// stick的数量
int total_len; // 木棍总长度
int cmp ( int a, int b){
	return a > b;
} 
/*
	sum 指当前拼凑的这根木棍的长度
	cur 指当前正在搜索的木棍下标 
	res 表示已经拼成的木棍的数量
	k 表示假设的单个木棍的长度   ->  min_len 
*/
bool dfs(int sum, int cur, int res, int k){
	if(res == stick_num){
		return true;
	}
	for(int i = cur; i < n; i++){
		//第i个被用了,或者与前一个木棍长度相同但是 前一个也没被用 
		//那么 这个也不能被用 
		if(vis[i] || (i && sticks[i] == sticks[i-1] && !vis[i-1])){
			continue;
		}
		if(sticks[i] + sum == k) {
			vis[i] = 1;
			if(dfs(0, 0, res+1, k)){
				return true;
			}
			vis[i] = 0; //虽然这步拼成了长度为x的木棍,但是剩下的不能成功拼凑,所以失败回溯 
			return false;
		}
		if(sticks[i] + sum < k) { //没拼好 
			vis[i] = 1;
			if(dfs(sticks[i] + sum, i + 1, res, k)){
				return true;
			}
			vis[i] = 0;
			if(!sum) return false;   // 注意: 区分sum=0和sum不等于0两种情况
		}
	}
	return false;
} 
int main(){
	while(cin >> n && n) {
		total_len = 0;
		for(int i = 0; i < n; i++) {
			cin >> sticks[i];
			total_len += sticks[i];
		}
		//从大到小排序  可以在比较少的次数里合成想要的那种长度 
		sort(sticks, sticks + n, cmp);
		int flag = 0;
		for(min_len = sticks[0]; min_len < total_len; min_len++){
			//因为初始的木棍是等长的 
			if(total_len % min_len == 0) {
				memset(vis, 0, sizeof(vis));
				stick_num = total_len / min_len; // 可能的最多木棍数量 
				if(dfs(0,0,0,min_len)){
					cout << min_len << endl;
					flag =  1;
					break;
				}
			}
		} 
		if(!flag) {
			cout << total_len << endl;
		}
	}
	return 0;
}

正方形6*6

#include 

using namespace std;

int pack1, pack2, pack3, pack4, pack5, pack6;
int packet3[] = { 0,5,3,1 };                                     //3*3剩余2*2空间的数量

int main()
{
    int bag;
    int box1, box2;
    while (cin >> pack1 >> pack2 >> pack3 >> pack4 >> pack5 >> pack6 && (pack1 + pack2 + pack3 + pack4 + pack5 + pack6))
    {
        bag = pack6 + pack5 + pack4 + (pack3 + 3) / 4;
        box2 = pack4 * 5 + packet3[pack3 % 4];
        if (pack2 > box2) bag += (pack2 - box2 + 8) / 9;
        box1 = bag * 36 - pack2 * 4 - pack3 * 9 - pack4 * 16 - pack5 * 25 - pack6 * 36;
        if (pack1 > box1) bag += (pack1 - box1 + 35) / 36;
        cout << bag << endl;
    }
}

链表

反转链表

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */


struct ListNode* reverseList(struct ListNode* head){
    struct ListNode *p = head;
    struct ListNode *pre = NULL;
    struct ListNode *ne = NULL;

    while (p) {
        ne = p->next;
        p->next = pre;
        pre = p;
        p = ne;
    }

    return pre;
}

相交链表

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {

    if (headA==NULL || headB==NULL) return NULL;

    struct ListNode *pa = headA;
    struct ListNode *pb = headB;

    while (pa && pb) {
        pa = pa->next;
        pb = pb->next;
    }

    if (pa == NULL) {
        pa = headB;
    }

    if (pb == NULL) {
        pb = headA;
    }

    while (pa && pb) {
        pa = pa->next;
        pb = pb->next;
    }

    if (pa == NULL) {
        pa = headB;
    }

    if (pb == NULL) {
        pb = headA;
    }

    while (pa && pb && pa != pb) {
        pa = pa->next;
        pb = pb->next;
    }

    return pa;
}
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {

    if (headA==NULL || headB==NULL) return NULL;

    struct ListNode *pa = headA;
    struct ListNode *pb = headB;
    
    while (pa != pb) {
        pa = pa == NULL ? headB : pa->next;
        pb = pb == NULL ? headA : pb->next;
    }

    return pa;
}

5. 最长回文子串

char * longestPalindrome(char * s){
    int len = strlen(s);
    int **arr = (int **)malloc(len * sizeof(int *));
    for (int i=0; i<len; i ++) {
        arr[i] = (int *)malloc(len * sizeof(int));
        memset(arr[i], 0, len * sizeof(int));
    }

    int i1 = 0;
    int i2 = 0;

    for (int y=0; y<len; y ++) {
        for (int x=0; x<=y; x ++) {
            if (x == y) {
                arr[x][y] = 1;
            } else if (x == y-1) {
                if (s[x] == s[y]) {
                    arr[x][y] = 1;
                }
            } else {
                if (x+1<len && y-1>=0 && arr[x+1][y-1] == 1 && s[x] == s[y]) {
                    arr[x][y] = 1;
                }
            }
            if (arr[x][y] == 1 && y-x > i2-i1) {
                i2 = y;
                i1 = x;

            }
        }
    }


    for (int i=0; i < len; i ++) {
        free(arr[i]);
    }
    free(arr);
    arr = NULL;

    int resLen = (i2-i1+2);
    char *res = (char *)malloc(resLen * sizeof(char));
    strncpy(res, s+i1, (resLen-1)*sizeof(char));
    res[resLen-1] = '\0';
    
    return res;
}

你可能感兴趣的:(力扣题目汇总)