leetcode刷题,总结,记录,备忘 77
来源:互联网 发布:新理念网络测试答案 编辑:程序博客网 时间:2024/06/05 23:04
leetcode77Combinations
Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.
For example,
If n = 4 and k = 2, a solution is:
[ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4],]这种题目一看就是很典型的递归题,我一开始也是这么往这上面思考的,但是写了个双层的循环,又加上递归,显而易见的结果超时了。后来没开窍,去翻人家的博客,发现了在单层循环中使用递归的方法,觉得很巧妙,其实之前有的题目都是使用了同样的递归的方式,我决定牢牢的记住这些方法,多读几遍代码,走两遍流程之后其实非常好懂,,,但是自己当时就是没想出这种方法,很惭愧。但是现在我已经掌握了,,,可是在自己掌握了之后,在leetcode上提交却无法通过,还是超时,,,我很郁闷,,把别人的代码直接拷上去却通过了,,,容我再研究研究。。。
自己研究之后提交的代码:
class Solution {public: vector<vector<int>> combine(int n, int k) { vector<vector<int> > result; vector<int> temp; function(1, n, k, result, temp); return result; } void function(int start, int n, int k, vector<vector<int> > & result, vector<int> & temp) { if (temp.size() == k) { result.push_back(temp); return; } for (int i = start; i <= n; ++i) { temp.push_back(i); function(start + 1, n, k, result, temp); temp.pop_back(); } }};
别人的代码,,可以提交通过:
class Solution {public: vector<vector<int>> combine(int n, int k) { vector<int> sub; vector<vector<int>> res; for (int i=1;i<=n;i++){ sub.push_back(i); com(res, sub, n, k, i); sub.pop_back(); } return res;}void com( vector<vector<int>> &res, vector<int> &sub, int n, int k, int start){ if(sub.size()==k) { res.push_back(sub); return; } for (int j=start+1; j<=n;j++){ sub.push_back(j); com(res, sub, n, k, j); sub.pop_back(); }}};
我很纳闷啊,,,感觉没什么不同之处,为什么我自己研究了别人的代码之后写的东西就提交不过,还超时了呢。。。。。
0 0
- leetcode刷题,总结,记录,备忘 77
- leetcode刷题。总结,记录,备忘 104
- leetcode刷题。总结,记录,备忘 100
- leetcode刷题。总结,记录,备忘 191
- leetcode刷题。总结,记录,备忘。168
- leetcode刷题, 总结,记录,备忘 171
- leetcode刷题 ,总结,记录,备忘。144
- leetcode刷题,总结,记录, 备忘 141
- leetcode刷题,总结,记录,备忘。116
- leetcode刷题,总结,记录,备忘。96
- leetcode刷题。记录,总结,备忘。217
- leetcode 刷题, 总结,记录,备忘 35
- leetcode刷题,总结,记录,备忘 226
- leetcode刷题,总结,记录,备忘 169
- leetcode刷题,总结,记录,备忘137
- leetcode刷题,总结,记录,备忘83
- leetcode刷题,总结,记录,备忘70
- leetcode刷题,总结,记录,备忘 108
- HUD 2051 Bitset
- Longest Common Substring最长公共子字符串
- Android实战简易教程-第五十八枪(AlarmManager类用法研究小实例)
- Shader 学习历程(一)——第一个shader
- 使用RecyclerView实现带Header和Footer的GridView
- leetcode刷题,总结,记录,备忘 77
- ios下使用AFNetworking通过Nginx服务器实现大文件上传
- ZOJ - 3822 Domination (概率DP)
- Linux战地日记——权限管理命令
- 求素数和的算法:很神奇,求大神解释一下代码.
- html5常见的表单元素
- hdu 5441 Travel(并查集+二分)
- 学测试第三个星期的知识总结
- Java网络编程之TCP