【leetcode】【medium】77. Combinations

77. Combinations

Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.

Example:

Input: n = 4, k = 2
Output:
[
  [2,4],
  [3,4],
  [2,3],
  [1,2],
  [1,3],
  [1,4],
]

題目鏈接:https://leetcode-cn.com/problems/combinations/

 

思路

法一:回溯法

這道題有一個去重的小規律:固定一個數a,找第二個結對的數b時只找比自己大的數。

本代碼的遞歸停止條件是k=1。

在可行情況下,要麼在k==1時返回新建的結果表,要麼在k>1時返回更新後的遞歸結果;只有在無法進入for循環時會返回空結果,此時說明該條路不是可行情況,直接跳過剪枝。

另一個剪枝的判定:當剩餘數字的數量比需求的少時,也是不可行的,因此可以直接剪掉;比如上圖的最右邊4分支。這一個判定寫在了for循環裏i的上界。

class Solution {
public:
    vector<vector<int>> combine(int n, int k) {
        vector<vector<int>> res;
        if(n<=0 || n<k) return res;
        return trace(n, k, 0);
    }
    vector<vector<int>> trace(int n, int k, int last){
        vector<vector<int>> res;
        for(int i=last+1; i<=n-k+1; ++i){
            if(k==1){
                vector<int> tmp = {i};
                res.push_back(tmp);
            }else{
                auto tmp = trace(n, k-1, i);
                if(tmp.size()<=0) continue;
                for(int j=0; j<tmp.size(); ++j){
                    tmp[j].push_back(i);
                }
                res.insert(res.begin(), tmp.begin(), tmp.end());
            }
        }
        return res;
    }
};

法二:二進制

這是分享看來的方法:https://leetcode-cn.com/problems/combinations/solution/zu-he-by-leetcode/

沒細看,待補全。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章