classSolution { public: vector<vector<int>> combine(int n, int k) { vector<vector<int>> ret; if (n <= 0) { return ret; } vector<int> cur; // DFSSolve(ret, cur, n, k, 1); DFSanother(ret, cur, 1, 0, n, k);
return ret; }
voidDFSSolve(vector<vector<int>> &ret, vector<int>cur, int n, int k, int level){ if (cur.size() == k) { ret.push_back(cur); return; } if (cur.size() > k) { return; }
for (int i = level; i <= n; i++) { cur.push_back(i); DFSSolve(ret, cur, n, k, i+1); cur.pop_back(); } }
voidDFSanother(vector<vector<int>> &ret, vector<int>&cur, int step, int selected, int n, int k){ if (selected == k) { ret.push_back(cur); return; } if (step == n + 1) { return; } DFSanother(ret, cur, step+1, selected, n, k); // not select cur.push_back(step); // select DFSanother(ret, cur, step+1, selected+1, n, k); cur.pop_back(); } };
Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.
The same repeated number may be chosen from candidates unlimited number of times.
Note:
All numbers (including target) will be positive integers.
The solution set must not contain duplicate combinations.
Example 1:
Input: candidates = [2,3,6,7], target = 7,
A solution set is:
[
[7],
[2,2,3]
]
Example 2:
Input: candidates = [2,3,5], target = 8,
A solution set is:
[
[2,2,2,2],
[2,3,3],
[3,5]
]
Constraints:
1 <= candidates.length <= 30
1 <= candidates[i] <= 200
Each element of candidate is unique.
1 <= target <= 500
classSolution { public: vector<vector<int>> combinationSum(vector<int>& candidates, int target) { vector<vector<int>> ret; vector<int> cur; int sum = 0; D(ret, cur, candidates, candidates.size(), target, 0, sum); return ret;
}
voidD(vector<vector<int>> &ret, vector<int> &cur, vector<int> &candidates, int size, int target, int step, int &sum){ if (sum == target) { ret.push_back(cur); return; } if (sum > target) { return; }
for (int i = step; i < size; i++) { cur.push_back(candidates[i]); sum+=candidates[i]; D(ret, cur, candidates, size, target, i, sum); sum -= cur.back(); // backtracking cur.pop_back(); } } };
也有逐个减去target的写法,就是sum和0的区别。
40. Combination Sum II - 20200910
Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.
Each number in candidates may only be used once in the combination.
Note:
All numbers (including target) will be positive integers.
The solution set must not contain duplicate combinations.
Example 1:
Input: candidates = [10,1,2,7,6,1,5], target = 8,
A solution set is:
[
[1, 7],
[1, 2, 5],
[2, 6],
[1, 1, 6]
]
Example 2:
Input: candidates = [2,5,2,1,2], target = 5,
A solution set is:
[
[1,2,2],
[5]
]
vector<vector<int>> combinationSum2(vector<int> &candidates, int target) { sort(candidates.begin(), candidates.end()); for (int i : candidates) { if (freq.empty() || i != freq.back().first) { freq.emplace_back(i, 1); } else { freq.back().second++; } } dfs(0, target); return ans; }
voiddfs(int pos, int rest) { if (rest == 0) { ans.push_back(tmpqueue); return; } if (pos == freq.size() || rest < freq[pos].first) return;
dfs(pos + 1, rest); // pos处的数字没有被选择
int cnt = min(rest / freq[pos].first, freq[pos].second); for (int i = 1; i <= cnt; i++) { tmpqueue.push_back(freq[pos].first); dfs(pos + 1, rest - i * freq[pos].first); } for (int i = 0; i < cnt; i++) tmpqueue.pop_back(); } };
216. Combination Sum III - 20200911
Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers.
Note:
All numbers will be positive integers.
The solution set must not contain duplicate combinations.
Example 1:
Input: k = 3, n = 7
Output: [[1,2,4]]
Example 2:
Input: k = 3, n = 9
Output: [[1,2,6], [1,3,5], [2,3,4]]
Given a non-empty binary tree, return the average value of the nodes on each level in the form of an array.
Example 1:
Input:
3
/ \
9 20
/ \
15 7
Output: [3, 14.5, 11]
Explanation:
The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11. Hence return [3, 14.5, 11].
Note:
The range of node’s value is in the range of 32-bit signed integer.
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ classSolution { public: vector<double> ret; vector<int> cntArr; vector<pair<int, int>> nodes; int cnt;
vector<double> averageOfLevels(TreeNode* root){ dfs(root, 0); ret = vector<double>(cnt+1, 0); cntArr = vector<int>(cnt+1, 0); for (int i = 0; i < nodes.size(); i++) { ret[nodes[i].second] += nodes[i].first; cntArr[nodes[i].second]++; } for (int i = 0; i <= cnt; i++) { ret[i] /= cntArr[i]; } return ret; }
voiddfs(TreeNode* root, int level){ nodes.push_back({root->val, level}); if (cnt < level) { cnt = level; } if (root->left) { dfs(root->left, level+1); } if (root->right) { dfs(root->right, level+1); } return; } }
79. Word Search - 20200913
Given a 2D board and a word, find if the word exists in the grid.
The word can be constructed from letters of sequentially adjacent cell, where “adjacent” cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.
classSolution { public: int m, n; int wordLen; boolexist(vector<vector<char>>& board, string word){ m = board.size(); n = board[0].size(); wordLen = word.length(); for (int i = 0;i<m;i++) pend.push_back(vector<int>(n, 0)); for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) { if (recur(board, i, j, word, 0)) returntrue; } returnfalse; }
boolrecur(vector<vector<char>> &board, int i, int j, string &word, int idx){ if (i < 0 || i >= m || j < 0 || j >= n || word[idx] != board[i][j]) returnfalse;
if (idx == wordLen-1) returntrue; char tmp = board[i][j]; // save tmp for backtracking board[i][j]='!'; if ( (recur(board, i - 1, j, word, idx+1) || recur(board, i + 1, j, word, idx+1) || recur(board, i, j - 1, word, idx+1) || recur(board, i, j + 1, word, idx+1)) ) returntrue; else { board[i][j]=tmp; returnfalse; } }
};
94. Binary Tree Inorder Traversal - 20200914
Given a binary tree, return the inorder traversal of its nodes’ values.
Example:
Input: [1,null,2,3]
1
\
2
/
3
Output: [1,3,2]
Follow up: Recursive solution is trivial, could you do it iteratively?
Note that different sequences are counted as different combinations.
Therefore the output is 7.
Follow up:
What if negative numbers are allowed in the given array?
How does it change the problem?
What limitation we need to add to the question to allow negative numbers?
Credits:
Special thanks to @pbrother for adding this problem and creating all test cases.
有一个dp的解法,但是c++由于超范围了用不了
1 2 3 4 5 6 7 8 9 10 11 12
intcombinationSum4(vector<int>& nums, int target){ vector<int> dp(target+1, 0); dp[0] = 1; for (int i = 0; i <= target; i++) for (int x: nums) if (x <= i) {
intcount(const vector<int> &nums, int target){ if (target == 0) return1; if (dp.count(target) != 0) return dp[target]; int res = 0; for (int i=0; i<size;i++) if (target-nums[i]>=0) res+=count(nums, target-nums[i]); dp[target] = res; return dp[target]; } };
37. Sudoku Solver - 20200915
Write a program to solve a Sudoku puzzle by filling the empty cells.
A sudoku solution must satisfy all of the following rules:
Each of the digits 1-9 must occur exactly once in each row.
Each of the digits 1-9 must occur exactly once in each column.
Each of the the digits 1-9 must occur exactly once in each of the 9 3x3 sub-boxes of the grid.
Empty cells are indicated by the character ‘.’.
A sudoku puzzle…
…and its solution numbers marked in red.
Note:
The given board contain only digits 1-9 and the character ‘.’.
You may assume that the given Sudoku puzzle will have a single unique solution.
Given a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus sum of all keys greater than the original key in BST.
Example:
Input: The root of a Binary Search Tree like this:
voiddfs(TreeNode* node){ if(!node) return; nodes.push_back(node->val); if (node->left) dfs(node->left); if (node->right) dfs(node->right); }
voidadd(TreeNode* node){ if(!node) return; int ori = node->val; for (int i = 0; i < nodes.size(); i++) if (nodes[i] > ori) node->val+=nodes[i]; if (node->left) add(node->left); if (node->right) add(node->right); } };
968. Binary Tree Cameras - 20200922
Given a binary tree, we install cameras on the nodes of the tree.
Each camera at a node can monitor its parent, itself, and its immediate children.
Calculate the minimum number of cameras needed to monitor all nodes of the tree.
Example 1:
Input: [0,0,null,0,0]
Output: 1
Explanation: One camera is enough to monitor all nodes if placed as shown.
Example 2:
Input: [0,0,null,0,null,0,null,null,0]
Output: 2
Explanation: At least two cameras are needed to monitor all nodes of the tree. The above image shows one of the valid configurations of camera placement.
Note:
The number of nodes in the given tree will be in the range [1, 1000].
Every node has value 0.
intminCameraCover(TreeNode* root){ ret = 0; if (dfs(root) == PNEED) ret++; return ret; }
intdfs(TreeNode* root){ if (!root) return NONEED; // 那么最底下的树被其父母覆盖就行 int left = dfs(root->left); int right = dfs(root->right);
if (left == PNEED || right == PNEED) { ret++; return HAS; } if (left == HAS || right == HAS) return NONEED; if (left == NONEED || right == NONEED) return PNEED; return NONEED; } };
617. Merge Two Binary Trees - 20200923
Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not.
You need to merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of new tree.
Given a binary search tree (BST) with duplicates, find all the mode(s) (the most frequently occurred element) in the given BST.
Assume a BST is defined as follows:
The left subtree of a node contains only nodes with keys less than or equal to the node’s key.
The right subtree of a node contains only nodes with keys greater than or equal to the node’s key.
Both the left and right subtrees must also be binary search trees.
For example:
Given BST [1,null,2,2],
1
\
2
/
2
return [2].
Note: If a tree has more than one mode, you can return them in any order.
Follow up: Could you do that without using any extra space? (Assume that the implicit stack space incurred due to recursion does not count).