美文网首页
32. Combinations FROM Leetcode

32. Combinations FROM Leetcode

作者: 时光杂货店 | 来源:发表于2017-03-17 17:02 被阅读6次

题目

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],
]

频度: 4

解题之法

class Solution {
public:
    vector<vector<int> > combine(int n, int k) {
        vector<vector<int> >res;
        if(n<k)return res;
        vector<int> temp(0,k);
        combine(res,temp,0,0,n,k);
        return res;
    }
    
    void combine(vector<vector<int> > &res,vector<int> &temp,int start,int num,int n ,int k){
        if(num==k){
            res.push_back(temp);
            return;
        }
        for(int i = start;i<n;i++){
            temp.push_back(i+1);
            combine(res,temp,i+1,num+1,n,k);
            temp.pop_back();
            }
        }
};

分析

DFS
The idea is using backtracking ,every time I push a number into vector,then I push a bigger one into it;
then i pop the latest one,and push a another bigger one...
and if I has push k number into vector,I push this into result;

相关文章

网友评论

      本文标题:32. Combinations FROM Leetcode

      本文链接:https://www.haomeiwen.com/subject/troenttx.html