<LeetCode OJ> 77. Combinations

Total Accepted: 69360 Total Submissions: 206274 Difficulty: Medium

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

分析:DONE

回溯法的典型,利用回溯法列举全部情况。

class Solution {  
public:  
    void dfs(vector<int> &subans, int start, int n, int k)//使用引用。有利于防止内存大爆炸  
    {  
        if (subans.size() == k)//已经获得答案,而且回溯  
        {  
            result.push_back(subans);   
            return ;//回溯  
        }  
        for (int i = start; i <= n; i++)  
        {  
            subans.push_back(i);  
            dfs(subans, i + 1, n, k);  
            subans.pop_back(); // 回溯完毕后去掉末尾元素。准备下一轮回溯法找答案  
        }  
    }  
    vector<vector<int> > combine(int n, int k) {  
        if (n < k || k == 0)   
            return result;  
        vector<int> subres;  
        dfs( subres, 1, n, k);  
        return result;  
    }  
private:
    vector<vector<int > > result;
}; 




这里显然也能够迭代实现,有空再来做做。


注:本博文为EbowTang原创。兴许可能继续更新本文。

假设转载。请务必复制本条信息。

原文地址:http://blog.csdn.net/ebowtang/article/details/50835803

原作者博客:http://blog.csdn.net/ebowtang

本博客LeetCode题解索引:http://blog.csdn.net/ebowtang/article/details/50668895

posted @ 2017-07-29 12:52  jzdwajue  阅读(149)  评论(0编辑  收藏  举报