由买买提看人间百态

topics

全部话题 - 话题: res
首页 上页 1 2 3 4 5 6 7 8 9 10 下页 末页 (共10页)
l***s
发帖数: 15
1
贡献一个 python
class Solution:
# @param an integer
# @return a list of string
def generateParenthesis(self, n):
bs='()'
res=['()']
if n==0:
return ''
elif n==1:
return res
for i in range(2,n+1):
leres=len(res)
for j in range(leres):
base=res[0]
del res[0]
lebase=len(base)
for k in range(lebase+1):
new = base[0:k]+bs+b... 阅读全帖
h*******t
发帖数: 2679
2
多写几个字:
res[a,b]=res[1,1]*res[0,3]+res[0,2]*res[2,5]
要求得到a=7;b=13
>>> 1+b+1 = b+2
相当于
res[a,b] = res[0,1] + res[1,1]
=> a=1,b=2;
h*******t
发帖数: 2679
3
多写几个字:
res[a,b]=res[1,1]*res[0,3]+res[0,2]*res[2,5]
要求得到a=7;b=13
>>> 1+b+1 = b+2
相当于
res[a,b] = res[0,1] + res[1,1]
=> a=1,b=2;
g**********y
发帖数: 14569
4
来自主题: JobHunting版 - 讨论一个g题
1. 拉格朗日定理:任何一个整数都可以分解成4个整数的平方和。
2. a_i <= sqrt(T)
3. BFS, search one square sum (0 ~ sqrt(T)), then two square sum, ... it
will end at most level 4.
程序可能可以更高效 --
public List split(int N) {
int n = (int) Math.sqrt(N);

int[] square = new int[n];
for (int i=0; i
List[] res = new List[N];
res[0] = new ArrayList();

Queue queue = new ArrayDeque();
q... 阅读全帖
f**********t
发帖数: 1001
5
来自主题: JobHunting版 - 问linkedin家一道题的followup
def nestSum(a, level):
res = 0
for x in a:
if isinstance(x, list):
res += nestSum(x, level + 1)
else:
res += int(x) * level
return res
def nestSumReverse(a):
res = 0
tmpSum = 0
level = 1
for x in a:
if isinstance(x, list):
curRes, curLevel = nestSumReverse(x)
res += curRes
level = max(curLevel + 1, level)
else:
tmpSum += int(x)
res += tmpSum * level
return r... 阅读全帖
f**********t
发帖数: 1001
6
来自主题: JobHunting版 - 问linkedin家一道题的followup
def nestSum(a, level):
res = 0
for x in a:
if isinstance(x, list):
res += nestSum(x, level + 1)
else:
res += int(x) * level
return res
def nestSumReverse(a):
res = 0
tmpSum = 0
level = 1
for x in a:
if isinstance(x, list):
curRes, curLevel = nestSumReverse(x)
res += curRes
level = max(curLevel + 1, level)
else:
tmpSum += int(x)
res += tmpSum * level
return r... 阅读全帖
z*********e
发帖数: 10149
7
来自主题: JobHunting版 - 这段word ladder II怎么改?
现在会超时,哪个地方应该优化一下?用的BFS
本机上一秒之内就出结果了,应该没有严重的算法问题吧
public List> findLadders(String start, String end, Set
dict) {
List> lastPaths = new ArrayList<>();
if(start == null || end == null) return lastPaths;
dict.add(end);
List top = new ArrayList<>();
top.add(start);
lastPaths.add(top);
if(start.equals(end)) return lastPaths;
int wordLen = start.length();
while(!dict.isEmpty()){ // same as ... 阅读全帖
S*******C
发帖数: 822
8
第一种更简洁,但s.toCharArray()要占用O(N)的空间吧?
public int titleToNumber(String s) {
int res = 0;
for (char c: s.toCharArray())
res = res * 26 + (c - 'A' + 1);
return res;
}
第二种有点啰嗦,但不需要额外占用O(N)的空间,不过s本来就要占O(N)的空间啊
public int titleToNumber1(String s) {
int res = 0;
for (int i = 0; i < s.length(); i++)
res = res * 26 + (s.charAt(i) - 'A' + 1);
return res;
}
哪种更好?
a***e
发帖数: 413
9
来自主题: JobHunting版 - Pascal's Triangle II 的优化解?
问道简单题,
Given an index k, return the kth row of the Pascal's triangle.
For example, given k = 3,
Return [1,3,3,1].
Note:
Could you optimize your algorithm to use only O(k) extra space?
对下面这种优化解总觉得不是很清楚。感觉如果不是自己想出来的东西下次又会忘,有
没有同学解释下原理?为啥内循环要从右忘左扫?多谢!
vector getRow(int rowIndex) {
vector res;
if (rowIndex<0) return res;

res.resize(rowIndex+1);
res[0]=1;

for (int i=1; i {
for (int j=i; j>=1; j-... 阅读全帖
n*******y
发帖数: 453
10
来自主题: JobHunting版 - 问一道Facebook近期电面题
上面的算法可以这样实现
def string(s)
tot = len(s)
if tot == 0
return s
cnt = 0
res = ""
index = 0
for index in range(tot):
if s[index] == "(":
res += "("
cnt += 1
elif (cnt > 0):
cnt -= 1
res += ")"
if cnt == 0:
return res
if cnt == len(res)
return ""
cnt2 = 0
index = len(res) - 1
while(cnt>0):
if (res[index] == "(")
cnt -= 1
else:
cnt2 += 1
index -= 1
return res[... 阅读全帖
f*******5
发帖数: 52
11
感谢楼主发面经!请问这道题是什么意思
2,用dfs写bfs,不难,循环+递归,到指定深度停止,返回有没有下一层,面试官挺
nice,很满意
打印lca的path那道题可以在递归之间传一个vector,里面保存path,用c++写了一下
TreeNode* lca_p(TreeNode* root, TreeNode* a, TreeNode* b, vector& res,
bool& found){
if(!root) return NULL;
if(root == a || root == b){
res.push_back(root->val);
if(a == b) found = true;
return root;
}
vector l_res;
vector r_res;
TreeNode* l = lca_p(root->left, a, b, l_res, found);
TreeNode* r = lca_p(root->right,... 阅读全帖
y***i
发帖数: 414
12
来自主题: JobHunting版 - 请问一道关于binary tree的题
public List getMaxNodePath(TreeNode node){
List max = new ArrayList();
max.add(node.val);
List res = new ArrayList();
res.add("");
findMaxPath(node, max, "", res);
return res;
}

public void findMaxPath(TreeNode node, List max, String path,
List res){
if(node == null){
return;
}
path = path.equals("") ? node.val + "" : path + "," + node.val;
... 阅读全帖
k****r
发帖数: 807
13
我写了一个,不知道可用不,先用DP找到最长subsequence的长度,complexity is O(
nlongn);
再用recursive找到所有可行解。
public static List> AllLongestIncreasingSubsequence(int[] nums
) {
int[] m = new int[nums.length + 1];
int L = 0;
for (int i = 0; i < nums.length; i++) {
int lo = 1;
int hi = L;
while (lo <= hi) {
int mid = (lo + hi) / 2;
if (nums[m[mid]] < nums[i]) lo = mid + 1;
else hi = mid - 1;
}... 阅读全帖
k****r
发帖数: 807
14
来自主题: JobHunting版 - 一道facebook面试题
some logic as follows:
helper(s, 0, 0, "", res, new HashSet set);
public void helper(String s, int idx, int blc, String tmp, List res,
Set set) {
if (idx == s.length()) {
if (blc == 0 && !set.contains(tmp)) {
res.add(tmp);
set.add(tmp);
}
return;
}
if (s.charAt(idx) == '(') {
helper(s, idx + 1, blc + 1, tmp + "(", res);
helper(s, idx + 1, blc + 1, tmp, res);
} else if (s.charAt(idx) == ')') ... 阅读全帖
o******y
发帖数: 446
15
来自主题: JobHunting版 - 帮忙看看怎么做这道G的题目
用链表和backtrack:
public int getMaxSum(int[] arr){
LinkedList q = new LinkedList<>();
for(int n: arr) q.add(n);
int[] res = new int[1];
res[0] = Integer.MIN_VALUE;
helper(res, q, 0);
return res[0];
}
void helper(int[] res, LinkedList q, int sum){
if(q.isEmpty()){
res[0] = Math.max(sum, res[0]);
return;
}
int size = q.size();
while(size-->0){
int v = q.rem... 阅读全帖
a**d
发帖数: 64
16
来自主题: JobHunting版 - 问两道fb题
第一题的java答案抄了一个,运行通过的。
https://github.com/nagajyothi/InterviewBit/blob/master/DynamicProgramming/
AvgSet.java
各路大神看看还有没有更优解。
// Sum_of_Set1 / size_of_set1 = total_sum / total_size, and so, Sum_of_Set1
= size_of_set1 * total_sum / total_size.
// Now we can just iterate on size_of_set1, and we would know the required
Sum_of_Set1.
static List res = new ArrayList();
static boolean[][][] dp;
public static List> partitionAverage(int[] num) {
List阅读全帖
y*******d
发帖数: 1674
17
来自主题: JobHunting版 - 问一道leetcode上的题目 combination sum
LC 39
code 如下
两处不明白
1. 为什么要先排序?
2. 为什么helper(res, target-candidates[i], tmp, candidates, i); 是i不是
i+1??
多谢指点
public List> combinationSum(int[] candidates, int target) {
List> res = new ArrayList>();
if (candidates == null || candidates.length == 0) {
return res;
}
Arrays.sort(candidates);
helper(res, target, new ArrayList(), candidates, 0);

return res;
}

void ... 阅读全帖

发帖数: 1
18
来自主题: JobHunting版 - Leetcode 689居然是fb的高频题?
叔这个题目是动态编程。
其实不是很复杂。
1. 就是你先算一下以k为长度,滑动窗口的和,放到一个数组里。
2. 从左到右计算 以i为起点,到i为止,最大值的窗口的起始index
比如说[1,3,2,0]
所对应[0,1,1] 因为 2 + 0 < 3 + 2
3.从右向左计算以z为为起点,从z向右考虑,最大窗口和的起始index
4.因为窗口不能重复,所以i + k <= j + k <= z
在j的范围内遍历并且更新结果就可以了。
代码如下:
class Solution {
public int[] maxSumOfThreeSubarrays(int[] nums, int k) {
int sum = 0, len = nums.length - k + 1;
int[] sums = new int[len];
for (int i = 0; i < nums.length; i++) {
sum += nums[i];
if (i >= k) sum -= nums[i... 阅读全帖

发帖数: 1
19
来自主题: JobHunting版 - 我也来问问LC的Maximal Rectangle
这题是84题的一个小拓展,不过不是很容易想到。
84题就是说如果直方图的高度是递增的,我们就入栈他的index以计算宽度,如果下降
了,就弹栈清算无法拓展面积的bar。
代码如下:
public int largestRectangleArea(int[] heights) {
Stack st = new Stack<>();
int[] nums = Arrays.copyOf(heights, heights.length + 1);
int res = 0;
for (int i = 0; i < nums.length; i++) {
while (!st.empty() && nums[st.peek()] >= nums[i]) {
int h = nums[st.pop()];
int w = st.empty() ? i : i - 1 - st.peek();
res = Math.max(res, w * h);
... 阅读全帖
f*********n
发帖数: 875
20
推动《排华法案》道歉议案通过是美国华人的历史使命
- 美国华人全国委员会再致华人社区的信
2011年5月26日,众议员赵美心 (Judy Chu, D-CA) ,比格特 (Jane Biggert, R-IL)
,考夫曼 (Mike Coffman, CO-R) 联名正式向众议院提
交了H. Res. 282议案,呼吁国会就《排华法案》这一历史错误进行道歉。据悉, 众议
院将在本月内对282号决议案进行投票表决。
亲爱的华人朋友们,
两年前的2010年5月27日,美国华人全国委员会(NCCA) 和其他几个华人团体的代表一
同前往美国众议院,递交了一封由一百多个华人团体和亚裔团体联署签名的请愿书,敦
促国会为1882年制定的充满种族歧视的《排华法案》向华人道歉。之后,华人社团加强
了联络,由美国华人全国委员会、美洲同源会、百人会、美华协会等发起了“1882计划
”,展开了从游说国会议员到起草“《排华法案》道歉议案”的一系列工作。
一年前的2011年5月26日,华裔民主党女众议员赵美心与两位共和党众议员比格特和考
夫曼联名正式向众议院提交了一项议案 (H. Res. 282),呼吁国... 阅读全帖
f*********n
发帖数: 875
21
推动《排华法案》道歉议案通过是美国华人的历史使命
- 美国华人全国委员会再致华人社区的信
2011年5月26日,众议员赵美心 (Judy Chu, D-CA) ,比格特 (Jane Biggert, R-IL)
,考夫曼 (Mike Coffman, CO-R) 联名正式向众议院提
交了H. Res. 282议案,呼吁国会就《排华法案》这一历史错误进行道歉。据悉, 众议
院将在本月内对282号决议案进行投票表决。
亲爱的华人朋友们,
两年前的2010年5月27日,美国华人全国委员会(NCCA) 和其他几个华人团体的代表一
同前往美国众议院,递交了一封由一百多个华人团体和亚裔团体联署签名的请愿书,敦
促国会为1882年制定的充满种族歧视的《排华法案》向华人道歉。之后,华人社团加强
了联络,由美国华人全国委员会、美洲同源会、百人会、美华协会等发起了“1882计划
”,展开了从游说国会议员到起草“《排华法案》道歉议案”的一系列工作。
一年前的2011年5月26日,华裔民主党女众议员赵美心与两位共和党众议员比格特和考
夫曼联名正式向众议院提交了一项议案 (H. Res. 282),呼吁国... 阅读全帖
m*****r
发帖数: 37
22
来自主题: Programming版 - Java弱弱请救几个小问题
我是最近刚转Java的弱弱,有几个小问题,请牛牛们轻拍。
这次转java,总算像是某位说的那样,原来c++转java也就分分钟的事儿。写得顺的时
候,边google边写,也可以写得稀里糊涂、腾云架雾、行云流水;可问题是bug一出现
,立马歇菜!比如,min stack, stack1.peek()==stack2.peek(),顶上的两个数字明明
是相等的,为什么会return false呢?想去google都不知道该搜什么。。。等把java刷
一遍lc就算我可以写java了?
我有个function, public boolean dfdjdf(){return dfkld;} 为什么它一定要我在最
后一句话加个return啊,方法里的逻辑到那一步早就应该已经return了啊?
还有就是,刷lc搭了个local的架,本来没什么心理障碍,可是每遇到有Node,
ListNode, TreeNode的题就一股无名火,我不知道该把这些定义的类塞到哪里?试过两
种:
public class getIntersectionNode {
public class ListNode {
... 阅读全帖
f*******o
发帖数: 150
23
来自主题: Biology版 - 2011 IF (1-180)
Rank, Abbreviated Journal Title, ISSN, Total Cites, 2011 Impact Factor, 5-
Year Impact
Factor, Immediacy Index, Articles Cited Half-life, Eigenfactor® Score,
Article Influence® Score
1 CA-CANCER J CLIN 0007-9235 10976 101.780 67.410 21.263
19 3.8 0.04502 24.502
2 NEW ENGL J MED 0028-4793 232068 53.298 50.075 11.484
349 7.8 0.66466 21.293
3 ANNU REV IMMUNOL 0732-0582 15990 52.761 42.901 9.174
23 ... 阅读全帖
r*****m
发帖数: 3619
24
来自主题: Biology版 - Wang Jun这么狠了吗?
Results: 46
Select item 25597018
1.
Exome-wide Sequencing Shows Low Mutation Rates and Identifies Novel Mutated
Genes in Seminomas.
Cutcutache I, Suzuki Y, Tan IB, Ramgopal S, Zhang S, Ramnarayanan K, Gan A,
Lee HH, Tay ST, Ooi A, Ong CK, Bolthouse JT, Lane BR, Anema JG, Kahnoski RJ,
Tan P, Teh BT, Rozen SG.
Eur Urol. 2015 Jan 14. pii: S0302-2838(14)01396-7. doi: 10.1016/j.eururo.
2014.12.040. [Epub ahead of print]
PMID: 25597018 [PubMed - as supplied by publisher] Free Article
Related citations... 阅读全帖
c********n
发帖数: 225
25
【记录历史】谁重复验证了NgAgo?
项目 结题
date: 2017年8月2日
updated: 2017年8月4日
Note2017080401: added a few notable reviews/summaries
---------------------------------------
- NBT retraction note:
http://www.nature.com/nbt/journal/v34/n7/full/nbt.3547.html#correction2
原文引用
“Retracted online 02 August 2017
We are retracting our study because of the continued inability of the
research community to replicate the key results in Figure 4, using the
protocols provided in our paper. In this figure we report that the
Natro... 阅读全帖
f***a
发帖数: 329
26
来自主题: Statistics版 - 【欢迎进来讨论】for loop in R
照例,还是我先胡说几句,:-)
在R里面能不用for loop就不应该用,尽量用vectorize的方式搞定一切。
对matrix/data.frame的row or col做运算,就用apply;(btw, same for array)
要对list, data.frame(essentially it is a list), vector的element做运算就用
lapply, sapply;
对不同id做运算,用tapply
下面是我的问题。
1)
# Way I:
for(i in 1:n){
res[i] <- myfunction(a[i], b[i], c[i])
}
# Way II:
res <- apply(cbind(a,b,c), 1, function(t)
myfunction(t[1], t[2], t[3])
)
这两种方法equivalent还是way II好一些呢?
2)
# Way I:
for(i in 1:n){
input <- i
...... # some heavy calculation
res[i] <- output
}
... 阅读全帖
v**e
发帖数: 8422
l*********y
发帖数: 142
28
来自主题: JobHunting版 - Josephus problem 有一句话没看懂
long long Joseph(long long n, int k)
{
long long d = n/k;
long long res = Joseph(n-d, k);
res -= n % k;
if (res < 0) res += n;
else res += res / (k-1);-------->这是要干什么?
return res;
}
没明白这句话,网上也没找到清楚的答案,wiki上说的很含糊,谁给解释以下,谢谢了
d****2
发帖数: 12
29
来自主题: JobHunting版 - facebook on site后多久给消息啊
You don't have to store the values (b,2b,4b, etc). Use recursion, it
actually stores it for you already.
int DivideR(int a, int& res, int div, int inc)
{
if(inc + inc > a)
{
res = div;
return inc;
}
int t1 = DivideR(a, res, div+div, inc+inc);
int t2 = t1 + inc;
if( t2 <= a)
{
res += div;
return t2;
}
return t1;
}
//assume positive number. Otherwise, check it and adjust accordingly.
int Divide(int a, int b)
{
if(a < b)
... 阅读全帖
h****n
发帖数: 1093
30
来自主题: JobHunting版 - Amazon intern first phone interview
17:12
1.
vector > FindAllPairs(vector input, int givenSum)
{
vector > res;
vector oneRes;
if(input.size()<1) return res;
int i = 0; j = input.size()-1;
while(i {
if(input[i]+input[j] else if(input[i]+input[j]>givenSum) j--;
else
{
oneRes.clear();
oneRes.push_back(input[i]);
oneRes.push_back(input[j]);
if(find(res.begin(), res.end(), oneRes)==res.en... 阅读全帖
h**6
发帖数: 4160
31
来自主题: JobHunting版 - Leetcode OJ的编译器是?
res没有截止符的空间,res截止符没有赋0,res没有释放内存。
char *res = new char[length + 2];
memset(res, 0, length + 2);
delete []res;
delete []res;
h****n
发帖数: 1093
32
和值有关系么,理解错了,以为是所有子树一样的节点,不过道理都一样
代码如下
vector GetAllUnivalNodes(TreeNode * root)
{
vector res;
helper(root, res);
return res;
}
bool helper(TreeNode * root, vector & res)
{
if(root==NULL)
return true;
bool leftRes = helper(root->left, res);
bool rightRes = helper(root->left, res);
if(!leftRes||!rightRes)
return false;
if(root->left&&root->val!=root->left->val)
return false;
if(root->right&&root->val!=r... 阅读全帖
h****n
发帖数: 1093
33
来自主题: JobHunting版 - G电面题 + 求祝福
Leetcode 上的原题
class Solution {
public:
vector plusOne(vector &digits) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int size = digits.size();
vector res;
if(size<1) return res;
//加1操作,只需要把初始值置为1即可
int carry = 1;
int i;
for(i=size-1;i>=0;i--)
{
//这里注意先push后更新carry的值,否则会有错误
res.push_back((digits[i]+carry)%10);
if(digits[i]+carry>9)... 阅读全帖
o****d
发帖数: 2835
34
来自主题: JobHunting版 - 做两道F的题吧
看了patrick9的思路 照着写了一个 c++
#define N 256
string findMostBeuatiful(string s){
string ans;
int len = s.size();
if(len<=1) return s;
int count[N]={0};
bool used[N]={false};
for(int i=0; i vector res;
for(int i=0; i char ch=s[i];
count[ch]--;
if(used[ch]) continue;
while(res.size()>0) {
char ch2=res.back();
if(ch20) {
res.pop_back();
used[ch2]=false... 阅读全帖
g********E
发帖数: 178
35
recursive的,用leetcode online judge里的格式,结果写成了这样:
//help function
void doinorder(TreeNode *root, vector &res){
if (root == NULL) return;
doinorder(root->left, res);
res.push_back(root->val);
doinorder(root->right, res);
}
//main function
vector inorderTraversal(TreeNode *root){
vector res;

doinorder(root, res);

return res;
}
--------
是不是太复杂了,有什么可以简化的么?要返回一个空vector是不是只能先新建一个空
的?多谢指教了!
L*******e
发帖数: 114
36
来自主题: JobHunting版 - G 家电面题目, 欢迎讨论!
试着写了一个recursive solution。
public static List match(String s){
List res = new ArrayList();
match(s.toCharArray(), 0, res);
return res;
}
private static void match(char[] array, int start, List res){
// search the first '?'
while (start < array.length && array[start] != '?'){
start++;
}
// no more '?', done
if (start == array.length){
res.add(new String(array));
return;
}
// replace '?' with 0 and 1
... 阅读全帖
b*********s
发帖数: 115
37
public class Solution {
public ArrayList postorderTraversal(TreeNode root) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
ArrayList res = new ArrayList();
visit(res, root);
return res;
}

private void visit(ArrayList res, TreeNode root) {
if (root == null) return;
visit(res, root.left);
visit(res, root.r... 阅读全帖
S******6
发帖数: 55
38
来自主题: JobHunting版 - leetcode上的Sort List那道题
pass了,不过不是replace
class Solution {
public:
ListNode *sortList(ListNode *head) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
vector res;
if(head == NULL || head->next == NULL) return head;
ListNode *cur = head;
while(cur)
{
res.push_back(cur->val);
cur = cur->next;
}
sort(res.begin(), res.end());
ListNode ... 阅读全帖
A*****o
发帖数: 284
39
来自主题: JobHunting版 - FB onsite面经加求bless
祝LZ拿到offer ~~
顺便献丑贴个email那题自己的完整代码,真心觉得不简单... 我是用了并查集来
统计合并,
请大牛给个简单点的解法吧,面试中是不可能有时间写这种代码的感觉...
#include
#include
#include
#include
#include
using namespace std;
/*
第二题是有这么一个class Contact,里面有一个String的name,和一个List
装着email address,是这个Contact有的address,用一个list装着是因为一个人有可
能有多个email,现在给你an array of Contact,比如
#1 John [j**[email protected]]
#2 Mary [m**[email protected]]
#3 John [j**[email protected]]
#4 John [j**[email protected], j**[email protected], j**[email protected]]
#5 Bob [bo... 阅读全帖
A*****o
发帖数: 284
40
来自主题: JobHunting版 - FB onsite面经加求bless
祝LZ拿到offer ~~
顺便献丑贴个email那题自己的完整代码,真心觉得不简单... 我是用了并查集来
统计合并,
请大牛给个简单点的解法吧,面试中是不可能有时间写这种代码的感觉...
#include
#include
#include
#include
#include
using namespace std;
/*
第二题是有这么一个class Contact,里面有一个String的name,和一个List
装着email address,是这个Contact有的address,用一个list装着是因为一个人有可
能有多个email,现在给你an array of Contact,比如
#1 John [j**[email protected]]
#2 Mary [m**[email protected]]
#3 John [j**[email protected]]
#4 John [j**[email protected], j**[email protected], j**[email protected]]
#5 Bob [bo... 阅读全帖
b*********s
发帖数: 115
41
来自主题: JobHunting版 - 一道L题
其实很短就可以写完
def fac(low, n):
if n == 1:
return [[]]
res = []
for i in xrange(low, n + 1):
if n % i == 0:
head = [i]
res += [head + tail for tail in fac(i, n / i)]
return res
def solve(n):
res = fac(2, n)
# 上面算出来的res最后一个是[n], 在开头插入1变成[1, n]
res[-1].insert(0, 1)
print res
测试:
input: 12 output: [[2, 2, 3], [2, 6], [3, 4], [1, 12]]
input: 100 output: [[2, 2, 5, 5], [2, 2, 25], [2, 5, 10], [2, 50], [4, 5, 5]
, [4, 25], [5, 20], [10... 阅读全帖
c*******r
发帖数: 610
42
来自主题: JobHunting版 - 请教个C++的基础问题
错误在于你的Point 是class template, 不同于一般的class,你用的时候成了Point
type, 不是Point type. T需要你explicit或者编译器可以自动 deduct type.
下面是修改的代码:
#include
#include
#include
using namespace std;
template
class Point {
public:
T x;
T y;
Point() : x(0), y(0) {}
Point(T a, T b) : x(a), y(b) {}
};
template //如果没有这一行,编译器不知道T是什么type,所以这个函数必
须是
//function template
T distance(const Point& i) { //这里必须是const Point& , 可能因为
... 阅读全帖
b*******g
发帖数: 57
43
来自主题: JobHunting版 - 请教个C++的基础问题
感谢前辈csiscoder经过实测的耐心细致的回复!给一千个赞!
运行了您修改的程序,bug free!
不过,还有个问题请求指点:
如果我将程序分别存在.h和.cpp文件里,为何有这样的报错呢:“error LNK2019:
unresolved external symbol”
--------------------------------------------------------------------
LeetCode.h内容为:
#include
#include
#include
template
class Point {
public:
T x;
T y;
Point() : x(0), y(0) {}
Point(T a, T b) : x(a), y(b) {}
};
//Find k closest points to origin
template
vector > findkClosestPoints(... 阅读全帖
T*******e
发帖数: 4928
44
来自主题: JobHunting版 - 求问permutation这个题
bool noSwap(const vector &num, int k, int i) {
for(int j=k; j if(num[j]==num[i]) return true; //see if any element from num[k] to
num[i-1] is equal to num[i]. If equal, that means someone equal to num[i]
has already taken this seat before. That possibility has been covered.
}
return false;
}
void permutationUniqueHelper(vector num, int n, int k, vector int> > &res) {
if(k==n) {
res.push_back(num);
} else {
for(int i=k; i<=n;... 阅读全帖
d********i
发帖数: 582
45
来自主题: JobHunting版 - 请教一道G的电面题。。
题目:给一个只包含0,1,*的 String,将所有的*替换成0或者1,返回所有的可能。
For example, “00*1*0” => {“001100”, “001110”, “000110”, “
000100”}
我的代码只输出: [“000100”, “000110”, “001110”], 但是少了“001100”.
我找不出原因。 谢谢。。
我的代码如下:
public static int depth;
public ArrayList combinationStarts(String s) {
int n = s.length();
char[] sc = s.toCharArray();
int starCount = 0;
for (int i = 0; i < n; i++) {
if (sc[i] == '*') {
starCount++;
}
}
depth = 0;
ArrayList res = n... 阅读全帖
d********i
发帖数: 582
46
来自主题: JobHunting版 - 请教一道G的电面题。。
请问recursion下什么时候要用static? 谢谢。。
代码run还是不对,什么都没有。。。。
public static ArrayList combinationStarts(String s) {
ArrayList res = new ArrayList();
dfs(s.toCharArray(), res, 0);
return res;
}
public static void dfs(char[] sc, ArrayList res, int depth) {
if (depth == sc.length) {
res.add(new String(sc));
} else {
for (int i = depth; i < sc.length; i++) {
if (sc[i] == '*') {
sc[i] = '0';
dfs(sc, r... 阅读全帖
a***e
发帖数: 413
47
Given n pairs of parentheses, write a function to generate all combinations
of well-formed parentheses.
For example, given n = 3, a solution set is:
"((()))", "(()())", "(())()", "()(())", "()()()"
Recursive 的写出来了,但DP的不知道怎么做,看了别人的code也不太懂,尤其是
for(int l=0;l buff[i].push_back(buff[j][k]+"("+buff[i-j-1][l]+")");
在做啥,为啥idx要i-j-1 等完全不清楚。
另外,大家有推荐学习DP的方法么?多谢
class Solution {
public:
vector generateParenthesis(int n) {
vecto... 阅读全帖
t**r
发帖数: 3428
48
来自主题: JobHunting版 - combination sum2的问题
测试:
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]
下面的代码是对的。
但是我就 不明白 if (num[i]!=pre) 是怎么保证 没有重复使用一个数字的呢。
我认为 反而会导致[1,1,6] 这种结果出问题,奇怪的是没有出问题
求教!
void dfs(vectorconst &num, int target, vector > &res,
vector &r,int st){
if (target<0){
return;
}else{
if (target==0){
res.push_back(r);
}else{
int pre = -1;
for... 阅读全帖
C****t
发帖数: 53
49
来自主题: JobHunting版 - 请教两个面试题
Greedy adding new meeting. Either add to a current room, or set a new room
for this meeting. O(n^2) time.
def findRoom( A):
A.sort(key = lambda x:x[0])
res = [[A[0]]]
for i in range(1,len(A)):
for j in range(len(res)):
if res[j][-1][-1] <= A[i][0]:
res[j].append(A[i])
break
if j == len(res) - 1:
res.append([A[i]])
return res
首页 上页 1 2 3 4 5 6 7 8 9 10 下页 末页 (共10页)