【回溯】組合
阿新 • • 發佈:2020-12-07
組合
給定兩個整數 n 和 k,返回 1 ... n 中所有可能的 k 個數的組合。
示例: 輸入:n = 4, k = 2
輸出:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/combinations
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。
組合就是從 n 個元素中取k 個元素。
由於組合不要求元素排序,所以我們直接按照序列從左往右深度優先遍歷來構造,符合個數 k 則儲存結果,達到邊界條件則回溯。
我們設定兩個陣列,一個 res 陣列來儲存最終答案,一個臨時陣列 temp 用來篩選答案。
vector<int> temp; //構造答案,符合要求則返回
vector<vector<int>> res; //儲存符合要求的所有temp陣列
深度優先遍歷的過程:
void dfs(int cur,int n,int k){ //cur當前遍歷位置,共n個元素,選擇k個元素 if(temp.size() == k){ //邊界條件一:符合要求的構造結果返回 res.push_back(temp); return; } if(cur == n+1) return; //邊界條件二:遍歷完畢 temp.push_back(cur); //取cur dfs(cur+1,n,k); //繼續向右遍歷 temp.pop_back(); //不取cur dfs(cur+1,n,k); //繼續向右遍歷 }
完整程式碼:
vector<int> temp; vector<vector<int>> res; void dfs(int cur,int n,int k){ //cur當前遍歷位置 if(temp.size() == k){ //邊界條件一:符合要求的構造結果返回 res.push_back(temp); return; } if(cur == n+1) return; //邊界條件二:遍歷完畢 temp.push_back(cur); //取cur dfs(cur+1,n,k); //繼續向右遍歷 temp.pop_back(); //不取cur dfs(cur+1,n,k); //繼續向右遍歷 } vector<vector<int>> combine(int n,int k){ //n個元素中選擇k個元素 dfs(1,n,k); //深度優先遍歷起點 return res; }
執行結果: