combine

来源:互联网 发布:vs打开数据库 编辑:程序博客网 时间:2024/05/16 10:53

Combinations

 Total Accepted: 14673 Total Submissions: 48919My Submissions

Combinations

 Total Accepted: 14673 Total Submissions: 48919My Submissions

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

[Thoughts]
Similar as "Conbination Sum". But here the terminate condition is "k", not sum.

[Code]
class Solution {
public:
    vector<vector<int> > combine(int n, int k) {
        vector<vector <int>> res;
        vector<int> solution;
        if (n<=0)
            return res;
        
        newcombine(n, k, 1, res, solution);
        return res;
    }
    
    void newcombine(int n, int k, int level, vector<vector<int>> &res, vector<int> &solution){
        if (solution.size()==k){      //这个事终止条件,达到K则返回
            res.push_back(solution);
            return;
        }
        
        for (int i=level; i<=n; i++){    //每次循环是从Level开始的,不是从i
            solution.push_back(i);
            newcombine(n, k, i+1, res, solution);
            solution.pop_back();   //这个pop_back是把最后一个元素pop出来,从而达到值变最后一个数的目的
        }
    }
};

0 0
原创粉丝点击