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
原创粉丝点击