32. Combinations FROM Leetcode

题目

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 > combine(int n, int k) {
        vector >res;
        if(n temp(0,k);
        combine(res,temp,0,0,n,k);
        return res;
    }
    
    void combine(vector > &res,vector &temp,int start,int num,int n ,int k){
        if(num==k){
            res.push_back(temp);
            return;
        }
        for(int i = start;i

分析

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)