Fork me on GitHub
hazelnutsgz

Why don't you come to your senses?


  • Home

  • About

  • Tags

  • Archives

Sum Root to Leaf Numbers

Posted on 2018-09-24

Descrpition

https://leetcode.com/problems/sum-root-to-leaf-numbers/description/

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
int sumNumbers(TreeNode* root) {
if (root == NULL) return 0;
int ret = 0;
int currentSum = 0;
this->sumLeafNode(root, ret, currentSum);
return ret;
}

void sumLeafNode(TreeNode* root, int& ret, int& currentSum) {
if (root == NULL) return;
currentSum = currentSum * 10 + root->val;
if (root->left == NULL && root->right == NULL) ret += currentSum;
this->sumLeafNode(root->left, ret, currentSum);
this->sumLeafNode(root->right, ret, currentSum);
currentSum = currentSum / 10;
}
};

Binary Tree Maximum Path Sum

Posted on 2018-09-24

Description

https://leetcode.com/problems/binary-tree-maximum-path-sum/description/

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int maxPathSum(TreeNode* root) {
int max = -10000;
this->findPath(root, max);
return max;
}

int findPath(TreeNode* root, int& max) {
if (root == NULL) return -100000;
int left = this->findPath(root->left, max);
if (left > max) max = left;
int right = this->findPath(root->right, max);
if (right > max) max = right;
int cur = root->val + (left >= 0 ? left : 0) + (right >= 0 ? right : 0);
if (cur > max) max = cur;

int bias = 0;
if (left > 0) bias = left;
if (right > 0 && right > left) bias = right;
return root->val + bias;
}
};

Populating Next Right Pointers in Each Node

Posted on 2018-09-22

Description

https://leetcode.com/problems/populating-next-right-pointers-in-each-node/description/

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/**
* Definition for binary tree with next pointer.
* struct TreeLinkNode {
* int val;
* TreeLinkNode *left, *right, *next;
* TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
* };
*/
class Solution {
public:
void connect(TreeLinkNode *root) {
if (root == NULL) return;
TreeLinkNode* cur = root;
while(cur != NULL) {
cur = this->linkSameLayer(cur);
}
}

TreeLinkNode* linkSameLayer(TreeLinkNode* parent) {
TreeLinkNode* traverse = parent->left;
if (traverse == NULL) return NULL;

TreeLinkNode* ret = traverse;
int count = 0;
while (parent != NULL) {
traverse->next = count % 2 ? parent->left : parent->right;
traverse = traverse->next;
parent = count % 2 ? parent : parent->next;
count += 1;
}
return ret;
}
};

Permutation Sequence

Posted on 2018-09-20

Description

https://leetcode.com/problems/permutation-sequence/description/

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40

class Solution {
public:
string getPermutation(int n, int k) {
vector<int> total = this->sumTotalList(n);
vector<int> remains_digits;
string ret(n, 'a');
for (int i = 1; i <= n; i++){
remains_digits.push_back(i);
}

int index = n - 1;
int remain = 0;
int count = n;

while (index >= 0){
int target_index = count * (k - 1) / total[index];
int target = remains_digits[target_index];
remains_digits.erase(remains_digits.begin() + target_index);
ret[n - 1 - index] = '0' + target;
k -= total[index - 1] * target_index;
index -= 1;
count -= 1;
}
return ret;
}

vector<int> sumTotalList(int n) {
vector<int> ret(1, 1);
if (n == 0 || n == 1) return ret;
int index = 2;
int sum = 1;
while (index <= n){
sum *= index;
ret.push_back(sum);
index += 1;
}
return ret;
}
};

Remove Duplicates from Sorted List II

Posted on 2018-09-11

Description

https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/description/

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
bool duplicate(struct ListNode* node) {
if (node == NULL || node->next == NULL) return false;
return node->val == node->next->val;
}


struct ListNode* deleteDuplicates(struct ListNode* head) {
if (head == NULL || head->next == NULL) return head;

struct ListNode* setinel_head = (struct ListNode* ) malloc(sizeof(struct ListNode));
setinel_head->next = head;


struct ListNode* pre = setinel_head;
struct ListNode* current = head;
while (current != NULL) {
if (duplicate(current) == false) {
pre = pre->next;
current = pre->next;
}else {
struct ListNode* nextNode = current->next;
while (nextNode != NULL && current->val == nextNode->val){
nextNode = nextNode->next;
}
pre->next = nextNode;
current = nextNode;
}
}
return setinel_head->next;
}

Substring with Concatenation of All Words

Posted on 2018-09-11

Description

https://leetcode.com/problems/substring-with-concatenation-of-all-words/description/

TLE Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
class Solution:
def findSubstring(self, s, words):
"""
:type s: str
:type words: List[str]
:rtype: List[int]
"""
dic = {}
alphabet = {}
for word in words:
if dic.get(word) is None:
dic[word] = 1
else:
dic[word] += 1
if alphabet.get(word[0]) is None:
alphabet[word[0]] = [word]
else:
alphabet[word[0]].append(word)

ret = []
i = 0
while i < len(s):
while i < len(s) and alphabet.get(s[i]) is None:
i += 1
if i == len(s):
return ret
if self.valid(i, s, dic, alphabet, ret) == True:
ret.append(i)
i += 1

return ret

def valid(self, i, s, word_dict, alphabet, ret):
if word_dict == {}:
return True
if i >= len(s):
return False

flag = False
item_list = alphabet.get(s[i])
if item_list is None:
return False


for item in item_list:
if i + len(item) <= len(s) and item == s[i : i + len(item)] and word_dict.get(item):
self.clear(word_dict, item, -1)
if self.valid(i + len(item), s, word_dict, alphabet, ret) == True:
flag = True
self.clear(word_dict, item, 1)

return flag

def clear(self, dic, item, incre):
t = dic.get(item)
if t is None:
dic[item] = 1
return
if t == 1 and incre < 0:
del dic[item]
return

dic[item] += incre
return

Solution

Palindrome Partitioning

Posted on 2018-09-09

Description

https://leetcode.com/problems/palindrome-partitioning/description/

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class Solution(object):
def partition(self, s):
"""
:type s: str
:rtype: List[List[str]]
"""
ret = []
st = []
if s is None or len(s) == 0:
return []
self.explore(0, s, st, ret)
return ret

def valid(self, s, start, end):
if end == start:
return True
middle = (start + end + 1) / 2
for i in range(start, middle):
if s[i] != s[start + end - i]:
return False
return True


def explore(self, start, s, st, ret):
if start == len(s):
ret.append(st[:])
return

for end in range(start, len(s)):
if self.valid(s, start, end) is False:
continue
st.append(s[start: end + 1])
self.explore(end + 1, s, st, ret)
st.pop()

return

Longest Valid Parentheses

Posted on 2018-09-09

Description

https://leetcode.com/problems/longest-valid-parentheses/description/

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution:
def longestValidParentheses(self, s):
"""
:type s: str
:rtype: int
"""
if s is None or len(s) == 0 or len(s) == 1:
return 0
dp = [0 for i in range(len(s))]
max_valid = 0
for i in range(1, len(dp)):
if s[i] == '(':
dp[i] = 0
else:
if s[i - 1] == '(':
dp[i] = (2 if i < 2 else (dp[i - 2] + 2) )
else:
temp = dp[i - 1]
if i - temp - 1 >= 0 and s[i - temp - 1] == '(':
dp[i] = temp + 2 + (0 if i - temp - 2 < 0 else dp[i - temp - 2])
else:
dp[i] = 0

max_valid = max(max_valid, dp[i])

print (dp)

return max_valid

Rotate Image

Posted on 2018-09-09

Description

https://leetcode.com/problems/rotate-image/description/

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution(object):
def rotate(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead.
"""
if matrix is None or len(matrix) == 0 or len(matrix) == 1:
return
size = len(matrix)
for layer in range(size / 2):
for offset in range(0, size - 1 - layer * 2):
temp = matrix[layer][layer + offset]
matrix[layer][layer + offset] = matrix[size - 1 - layer - offset][layer]
matrix[size - 1 - layer - offset][layer] = matrix[size-1-layer][size - 1 - layer - offset]
matrix[size-1-layer][size - 1 - layer - offset] = matrix[layer + offset][size - 1 - layer]
matrix[layer + offset][size - 1 - layer] = temp
return

Binary Search Tree Iterator

Posted on 2018-09-08

Description

https://leetcode.com/problems/binary-search-tree-iterator/description/

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class BSTIterator {
public:
BSTIterator(TreeNode *root) {
this->nodeStack = new stack<TreeNode*>();
this->current = root;
while(this->current != NULL) {
this->nodeStack->push(this->current);
this->current = this->current->left;
}
}

/** @return whether we have a next smallest number */
bool hasNext() {
return !this->nodeStack->empty();
}

/** @return the next smallest number */
int next() {
this->current = this->nodeStack->top();
this->nodeStack->pop();
int ret = this->current->val;

this->current = this->current->right;
while(this->current != NULL) {
this->nodeStack->push(this->current);
this->current = this->current->left;
}
return ret;
}
private:
TreeNode* current;
stack<TreeNode*>* nodeStack;
};

/**
* Your BSTIterator will be called like this:
* BSTIterator i = BSTIterator(root);
* while (i.hasNext()) cout << i.next();
*/
1…121314…21

hazelnutsgz

A normal coder

210 posts
9 tags
Github LinkedIn
© 2019 hazelnutsgz
本站访客数:
|
Theme — NexT.Muse v5.1.4
总访问量次 | 总访客人 |