Leetcode日记(8)

本文介绍两种算法实现:一是生成所有合法的n对括号组合;二是交换链表中相邻节点的方法。通过递归策略解决括号生成问题,并提供C++代码示例。同时,针对链表节点交换问题给出一种简洁有效的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Generate Parentheses

问题描述

        Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
        For example, given n = 3, a solution set is:

[
  "((()))",
  "(()())",
  "(())()",
  "()(())",
  "()()()"
]

分析

       使用递归的策略求解,使用n记录“(”的个数,m记录“)”的个数,当m和n都为0时,代表生成了一种可能。

解答

class Solution {
public:
    vector<string> generateParenthesis(int n) {
        vector<string> result;
        add(result, "", n, 0);
        return res;
    }
    void add(vector<string> &res, string str, int n, int m)
    {
        if(n==0 && m==0) 
            res.push_back(str);
        if(m > 0)
            add(res, str+")", n, m-1); 
        if(n > 0)
            addr(res, str+"(", n-1, m+1); 
    }
};

Swap Nodes in Pairs

问题描述

        Given a linked list, swap every two adjacent nodes and return its head.
        For example,
        Given 1->2->3->4, you should return the list as 2->1->4->3.
        Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.

分析

       依次判别链表两个元素不为空时交换它们的位置即可。

解答

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        ListNode result(0);
        result.next = head;
        ListNode *p = &result;
        for ( ; head != NULL && head->next != NULL; p = head, head = p->next)
        {
            p->next = head->next;
            p = p->next;
            head->next = p->next;
            p->next = head;
        }
        return result.next;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值