中文


[leetcode] Combinations

Combinations Given two integers n and k, return all possible combinations of k numbers out of 1 … n. For example, If n = 4 and k = 2, a solution is: [ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4], ] tag: backtracking 回溯问题,用递归求解就好。 class Solution { public: vector<vector<int> > combine(int […]


[leetcode] Longest Valid Parentheses

Longest Valid Parentheses Given a string containing just the characters ‘(‘ and ‘)’, find the length of the longest valid (well-formed) parentheses substring. For “(()”, the longest valid parentheses substring is “()”, which has length = 2. Another example is “)()())”, where the longest valid parentheses substring is “()()”, which […]


[leetcode] Next Permutation

Next Permutation Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers. If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order). The replacement must be in-place, do not allocate extra memory. Here are some examples. […]


[leetcode] N-Queens II

N-Queens II Follow up for N-Queens problem. Now, instead outputting board configurations, return the total number of distinct solutions. tag: backtracking 此题与上一题非常相似,只是把“输出所有可能情况”改成了“输出所有可能情况的个数”。详细解析请看上一题的结题报告: N-Queens class Solution { public: int totalNQueens(int n) { if(n == 0){ return 0; } int queen[n] = {0}; int sum = 0; for(int i = 0; i < […]


[leetcode] N-Queens

N-Queens The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other. Given an integer n, return all distinct solutions to the n-queens puzzle. Each solution contains a distinct board configuration of the n-queens’ placement, where ‘Q’ and ‘.’ […]


[leetcode] Linked List Cycle II

Linked List Cycle II Given a linked list, return the node where the cycle begins. If there is no cycle, return null. Follow up: Can you solve it without using extra space? 与上一题类似,这里我直接复用并修改了上一题的代码。 我们这样来想: 设置两个指针fast和slow,fast指针每次走2步,slow指针每次走1步。 假设进入环之前的路径长为n,环的长度为m。那么当slow指针进入环的第一个节点时,slow指针走了n步,fast指针在环里走了n步。两个指针的距离为m-n步。slow指针每走1步,fast指针都会追近1步。那么,当slow指针走了m-n步时,两个指针相遇。此时,fast-slow指针距离下次抵达环入口的距离为n步。 在fast-slow指针相遇时,在链表入口处放置一个指针p,p指针每次走一步。slow指针也每次走一步。这样当slow和p都再走n步时,两者在环的入口处相遇。即返回结果。 /** * Definition for singly-linked list. * struct ListNode { * int val; […]