Skip to content

Commit 4f8f54a

Browse files
committed
Add solution #93
1 parent 57098bb commit 4f8f54a

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,7 @@
7373
83|[Remove Duplicates from Sorted List](./0083-remove-duplicates-from-sorted-list.js)|Easy|
7474
88|[Merge Sorted Array](./0088-merge-sorted-array.js)|Easy|
7575
90|[Subsets II](./0090-subsets-ii.js)|Medium|
76+
93|[Restore IP Addresses](./0093-restore-ip-addresses.js)|Medium|
7677
94|[Binary Tree Inorder Traversal](./0094-binary-tree-inorder-traversal.js)|Easy|
7778
98|[Validate Binary Search Tree](./0098-validate-binary-search-tree.js)|Medium|
7879
100|[Same Tree](./0100-same-tree.js)|Easy|
+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/**
2+
* 93. Restore IP Addresses
3+
* https://leetcode.com/problems/restore-ip-addresses/
4+
* Difficulty: Medium
5+
*
6+
* A valid IP address consists of exactly four integers separated by single
7+
* dots. Each integer is between 0 and 255 (inclusive) and cannot have
8+
* leading zeros.
9+
*
10+
* For example, "0.1.2.201" and "192.168.1.1" are valid IP addresses, but
11+
* "0.011.255.245", "192.168.1.312" and "[email protected]" are invalid IP addresses.
12+
*
13+
* Given a string s containing only digits, return all possible valid IP
14+
* addresses that can be formed by inserting dots into s. You are not allowed
15+
* to reorder or remove any digits in s. You may return the valid IP addresses
16+
* in any order.
17+
*/
18+
19+
/**
20+
* @param {string} s
21+
* @return {string[]}
22+
*/
23+
var restoreIpAddresses = function(s) {
24+
return backtrack([], s);
25+
};
26+
27+
function backtrack(order, string, result = []) {
28+
const isValid = s => +s <= 255 && `${+s}` === s;
29+
30+
if (order.length === 3 && isValid(string)) {
31+
result.push([...order, string].join('.'));
32+
} else {
33+
for (let index = 1; index < 4; index++) {
34+
const sliced = string.slice(0, index);
35+
if (isValid(sliced)) {
36+
backtrack([...order, sliced], string.slice(index), result);
37+
}
38+
}
39+
}
40+
41+
return result;
42+
}

0 commit comments

Comments
 (0)