陣列中n,k 的輸出
阿新 • • 發佈:2019-01-01
// // Created by dongfucai on 2019/1/1. // #include <vector> #include <iostream> using namespace std; //If n = 4 and k = 2, a solution is: //[ //[2,4], //[3,4], //[2,3], //[1,2], //[1,3], //[1,4], //] class Solution { public: void solution (int n, int k) { if (n < k) { return; } vector<vector<int> > res; vector<int> temp; int pos = 1; dfs(k, n, pos, temp, res); } void dfs(int &k, int &n, int pos, vector<int> temp, vector<vector<int> > &res) { if (temp.size() == k) { for (int i = 0; i < k; ++i) { cout << temp[i] << " "; } cout << endl; res.push_back(temp); return; } for (int i = pos; i <= n; ++i) { // 選擇基本是都是for 或者 if temp.push_back(i); dfs(k, n, i + 1, temp, res); // 這個pos位置要注意一下啊,pos + 1 ,還是 i + 1 有條件的選擇 temp.pop_back(); } } }; int main() { Solution s; s.solution(4, 2); }