classSolution { voiddfs(int n, int left, string cur, vector<string> & ans){ if(!n && !left){ ans.push_back(cur); return; } if(n > 0) dfs(n - 1, left + 1, cur + '(', ans); if(left > 0) dfs(n, left - 1, cur + ')', ans); } public: vector<string> generateParenthesis(int n){ vector<string> ans; dfs(n, 0, "", ans); return ans; } };
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution(object): defgenerateParenthesis(self, n): """ :type n: int :rtype: List[str] """ ans = [] self.dfs(n, 0, "", ans) return ans
defdfs(self, n, left, cur, ans): ifnot n andnot left: ans.append(cur) return if n > 0: self.dfs(n - 1, left + 1, cur + '(', ans) if left > 0: self.dfs(n, left - 1, cur + ')', ans)
39. Combination Sum
Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
The same repeated number may be chosen from C unlimited number of times.
Note:
All numbers (including target) will be positive integers.
Elements in a combination (_a_1, _a_2, … , _a_k) must be in non-descending order. (ie, _a_1 ≤ _a_2 ≤ … ≤ _a_k).
The solution set must not contain duplicate combinations.
For example, given candidate set 2,3,6,7 and target 7, A solution set is: [7][2, 2, 3]
classSolution(object): defcombinationSum(self, candidates, target): """ :type candidates: List[int] :type target: int :rtype: List[List[int]] """ candidates.sort() ans, _path = [], [] self.solve(0, target, _path, ans, candidates) return ans
defsolve(self, cur, target, _path, ans, candidates): if target == 0: ans.append(_path[:]) # use _path will be wrong. return
while cur < len(candidates): if candidates[cur] <= target: _path.append(candidates[cur]) self.solve(cur, target - candidates[cur], _path, ans, candidates) _path.pop() while cur + 1 < len(candidates) and candidates[cur] == candidates[cur + 1]: cur += 1 cur += 1
40. Combination Sum II
Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
Each number in C may only be used once in the combination.
Note:
All numbers (including target) will be positive integers.
Elements in a combination (_a_1, _a_2, … , _a_k) must be in non-descending order. (ie, _a_1 ≤ _a_2 ≤ … ≤ _a_k).
The solution set must not contain duplicate combinations.
For example, given candidate set 10,1,2,7,6,1,5 and target 8, A solution set is: [1, 7][1, 2, 5][2, 6][1, 1, 6]
classSolution(object): defcombinationSum2(self, candidates, target): """ :type candidates: List[int] :type target: int :rtype: List[List[int]] """ candidates.sort() ans, _path = [], [] self.solve(0, target, _path, ans, candidates) return ans
defsolve(self, cur, target, _path, ans, candidates): if target == 0: ans.append(_path[:]) # use _path will be wrong. return
while cur < len(candidates): if candidates[cur] <= target: _path.append(candidates[cur]) self.solve(cur + 1, target - candidates[cur], _path, ans, candidates) _path.pop() while cur + 1 < len(candidates) and candidates[cur] == candidates[cur + 1]: cur += 1 cur += 1
51. 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 '.' both indicate a queen and an empty space respectively.
For example, There exist two distinct solutions to the 4-queens puzzle:
classSolution { public: inlineboolcheck(vector<int> &place, int cur){ for (int j = 0; j < cur; j++) if (place[cur] == place[j] || abs(place[cur] - place[j]) == cur - j) returnfalse; returntrue; }
voidsolve(int cur, int n, vector<int> &place, vector<vector<string>> &ans){ if (cur == n){ vector<string> res; for (int k = 0; k < n;k++) for (int i = 0; i < n;i++) if (place[i] == k){ string temp(n, '.'); temp[i] = 'Q'; res.push_back(temp); } ans.push_back(res); return; } for (int i = 0; i < n; i++) { place[cur] = i; if (check(place, cur)) solve(cur + 1, n, place, ans); } }
classSolution: # @return a list of lists of string defsolveNQueens(self, n): self.ans=[] place=[0]*n self.solve(0, n,place) return self.ans defcheck(self,cur,place): for i inrange(0,cur): if place[i]==place[cur] orabs(place[i]-place[cur])==cur-i: returnFalse returnTrue defsolve(self,cur,n,place): if cur==n: temp=[] for k inrange(0,n): for i inrange(0,n): if place[i]==k: L='.'*i+'Q'+'.'*(n-i-1) temp.append(L) self.ans.append(temp) return for i inrange(0,n): place[cur]=i if(self.check(cur,place)): self.solve(cur + 1, n, place)
classSolution: # @return an integer deftotalNQueens(self, n): self._cnt=0 place=[0]*n self.solve(0, n,place) return self._cnt defcheck(self,cur,place): for i inrange(0,cur): if place[i]==place[cur] orabs(place[i]-place[cur])==cur-i: returnFalse returnTrue defsolve(self,cur,n,place): if cur==n: self._cnt += 1 return for i inrange(0,n): place[cur]=i if(self.check(cur,place)): self.solve(cur + 1, n, place)
classSolution { public: voidsolve( int cnt, int cur, int n, int k, vector<int>& vis, vector<vector<int> > & ans){ if (cnt == k){ ans.push_back(vis); return; } for (int i = cur; i < n; i++){ vis.push_back(i+1); solve(cnt+1,i+1, n, k,vis, ans); vis.pop_back(); } } vector<vector<int> > combine(int n, int k) { vector<vector<int> > ans; vector<int> vis; solve(0,0, n, k,vis, ans); return ans; } };
classSolution { privatevoiddfs(int cur, List<Integer> res, finalint n, finalint k, List<List<Integer>> ans) { if (res.size() == k) { ans.add(newArrayList<>(res)); return; } for (inti= cur; i <= n; i++) { res.add(i); dfs(i + 1, res, n, k, ans); res.remove(res.size() - 1); } }
public List<List<Integer>> combine(int n, int k) { List<Integer> res = newArrayList<>(); List<List<Integer>> ans = newArrayList<>(); dfs(1, res, n, k, ans); return ans; } }
Python
现在的貌似TLE了,原来AC的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution: # @return a list of lists of integers defcombine(self, n, k): ans,res=[],[] self.solve(res, 0, 0, n, k, ans) return ans defsolve(self,res,cnt,cur,n,k,ans): if cnt==k: ans.append(res[:]) return for i inrange(cur,n): res.append(i+1) self.solve(res, cnt+1, i+1, n, k, ans) res.pop()
78. Subsets
Given a set of distinct integers, S, return all possible subsets.
Note:
Elements in a subset must be in non-descending order.
The solution set must not contain duplicate subsets.
public List<List<Integer>> subsets(int[] nums) { List<Integer> res = newArrayList<>(); List<List<Integer>> ans = newArrayList<>(); dfs(0, res, nums, ans); return ans; } }
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution(object): defsubsets(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ ans,res=[],[] self.solve(0, len(nums), nums, res, ans) return ans defsolve(self,cur,n,nums,res,ans): ans.append(res[:]) for i inrange(cur,n): res.append(nums[i]) self.solve(i+1, len(nums), nums, res, ans) res.pop()
79. Word Search
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.
For example, Given board =
1 2 3 4 5
[ ["ABCE"], ["SFCS"], ["ADEE"] ]
word = "ABCCED", -> returns true, word = "SEE", -> returns true, word = "ABCB", -> returns false.
classSolution: # @param board, a list of lists of 1 length string # @param word, a string # @return a boolean defexist(self, board, word): vis = [[0for i inrange(len(board[0]))]for j inrange(len(board))] m , n = len(board) , len(board[0]) self.dx , self.dy= [1,-1,0,0], [0,0,1,-1] for i inrange(m): for j inrange(n): if board[i][j]==word[0]: vis[i][j]=True if(self.dfs(i,j,1,vis,board,word)): returnTrue vis[i][j]=False returnFalse defdfs(self,x,y,cur,vis,board,word): if cur==len(word): returnTrue if cur > len(word): returnFalse for k inrange(4): nx,ny=x+self.dx[k] , y + self.dy[k] if nx < 0or nx >= len(board) or ny <0or ny >= len(board[0]): continue if board[nx][ny]==word[cur] andnot vis[nx][ny]: vis[nx][ny]=True if(self.dfs(nx, ny, cur+1, vis, board, word)): returnTrue vis[nx][ny]=False returnFalse
classSolution(object): defdfs(self, cur, x, y, vis, board, word): if cur == len(word): returnTrue if x < 0or y < 0or x >= len(board) or y >= len(board[0]): returnFalse if vis[x][y] or word[cur] != board[x][y]: returnFalse vis[x][y] = True for dx, dy in ((1, 0), (-1, 0), (0, 1), (0, -1)): if self.dfs(cur + 1, x + dx, y + dy, vis, board, word): returnTrue vis[x][y] = False returnFalse defexist(self, board, word): """ :type board: List[List[str]] :type word: str :rtype: bool """ ifnot board ornot board[0]: returnFalse vis = [[False] * len(board[0]) for _ inrange(len(board))] for i inrange(len(board)): for j inrange(len(board[i])): if board[i][j] == word[0] and self.dfs(0, i, j, vis, board, word): returnTrue returnFalse
90. Subsets II
Given a collection of integers that might contain duplicates, S, return all possible subsets.
Note:
Elements in a subset must be in non-descending order.
The solution set must not contain duplicate subsets.
classSolution { public: voidsolve(int cur, int n, vector<int> &nums, vector<int> &res,vector<vector<int>> & ans){ ans.push_back(res); for (int i = cur; i < n; i++){ res.push_back(nums[i]); solve(i+1, n, nums, res, ans); res.pop_back(); while (i + 1 < n && nums[i] == nums[i + 1]) i++; } }
classSolution(object): defsubsetsWithDup(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ nums.sort() ans, res = [], [] self.solve(0, len(nums), nums, res, ans) return ans
defsolve(self, cur, n, nums, res, ans): ans.append(res[:]) i = cur while i < n: res.append(nums[i]) self.solve(i + 1, len(nums), nums, res, ans) while i + 1 < n and nums[i] == nums[i + 1]: i += 1 res.pop() i += 1
200. Number of Islands
Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.
classSolution: # @param grid, a list of list of characters # @return an integer defnumIslands(self, grid): ifnot grid ornot grid[0]:return0 m,n=len(grid),len(grid[0]) vis = [[Falsefor j in xrange(n)]for i in xrange(m)] self.dx,self.dy=[1,-1,0,0],[0,0,1,-1] ans = 0 for i in xrange(m): for j in xrange(n): if grid[i][j]=='1'andnot vis[i][j]: vis[i][j]=True self.dfs(i,j,grid,vis) ans+=1 return ans
defdfs(self,x,y,grid,vis): for k in xrange(4): nx,ny=x+self.dx[k],y+self.dy[k] if nx<0or ny<0or nx >=len(grid) or ny>=len(grid[0])\ or grid[nx][ny]=='0'or vis[nx][ny]: continue vis[nx][ny]=True self.dfs(nx,ny,grid,vis)
216. Combination Sum III
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.
Ensure that numbers within the set are sorted in ascending order.
Given a string of numbers and operators, return all possible results from computing all the different possible ways to group numbers and operators. The valid operators are +, - and *. Example 1
defdfs(self, s, dp): if s in dp: return dp[s] ans = [] n = len(s) for i in xrange(n): if s[i] notin ["+", "-", "*"]: continue res1, res2 = self.dfs(s[:i], dp), self.dfs(s[i + 1:], dp) for x in res1: for y in res2: if s[i] == '+': ans.append(x + y) elif s[i] == '-': ans.append(x - y) elif s[i] == '*': ans.append(x * y) ifnot ans: ans.append(int(s)) dp[s] = ans return ans
282. Expression Add Operators
Given a string that contains only digits 0-9 and a target value, return all possibilities to add binary operators (not unary) +, -, or * between the digits so they evaluate to the target value.
typedef long long int LL; classSolution { public: vector<string> addOperators(string num, int target) { vector<string> ans; dfs(0, "", 0, 0, ans, num.length(), num, target); return ans; }
void dfs(int cur, string path, LL pre, LL val, vector<string> & ans, const int n, const string &num, const int target) { if (cur == n && pre + val == target) { ans.push_back(path); return; } LL x = 0; for (int i = cur; i < n; i++) { x = x * 10 + (num[i] - 48); // - '0' it is48 string str_x = to_string(x); if (cur != 0) { dfs(i + 1, path + "+" + str_x, pre + val, x, ans, n, num, target); dfs(i + 1, path + "-" + str_x, pre + val, -x, ans, n, num, target); dfs(i + 1, path + "*" + str_x, pre, val * x, ans, n, num, target); } else dfs(i + 1, str_x, 0, x, ans, n, num, target); if (num[cur] == '0') break; } } };
797. All Paths From Source to Target
Given a directed, acyclic graph of N nodes. Find all possible paths from node 0 to node N-1, and return them in any order.
The graph is given as follows: the nodes are 0, 1, ..., graph.length - 1. graph[i] is a list of all nodes j for which the edge (i, j) exists.
Example: Input: [[1,2], [3], [3], []] Output: [[0,1,3],[0,2,3]] Explanation: The graph looks like this: 0--->1
v v 2--->3 There are two paths: 0 -> 1 -> 3 and 0 -> 2 -> 3.
Note:
The number of nodes in the graph will be in the range [2, 15]. You can print different paths in any order, but you should keep the order of nodes inside one path.