【LeetCode】Combinations

来源:互联网 发布:水利水电计价软件 编辑:程序博客网 时间:2024/06/17 05:24

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],]
思路:组合,DFS,深度优先遍历,和【LeetCode】Combination Sum II、【LeetCode】Combination Sum思路相同。详见:

http://blog.csdn.net/cyangc/article/details/38718843

http://blog.csdn.net/cyangc/article/details/38648533

class Solution {public:    void comb(int begin,int end,int num,int target,vector<vector<int> > &ret,vector<int> &path){        if(num>target)return;        if(num == target){            ret.push_back(path);            return;        }        for(int i=begin;i<=end;i++){            path.push_back(i);            comb(i+1,end,num+1,target,ret,path);            path.pop_back();        }            }    vector<vector<int> > combine(int n, int k) {        vector<vector<int> > ret;        vector<int> path;        comb(1,n,0,k,ret,path);        return ret;    }};





0 0