1. 程式人生 > ><LeetCode OJ> 77. Combinations

<LeetCode OJ> 77. Combinations

net ble height clas con leetcode code consola 回溯法

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

&lt;LeetCode OJ&gt; 77. Combinations