Journey of LeetCode|DAY 21
Preface
This is a new day to start my backtracking algorithm journey.
Learn something new and keep reviewing what I learnt before.
1. Combinations
LeetCode Link: 77. Combinations
Given two integers n and k, return all possible combinations of k numbers chosen from the range [1, n].
You may return the answer in any order.
Analysis and Solution
Recursion And Backtrack
LeetCode C++ as followings Recursion And Backtrack
class Solution {
private:
vector<vector<int>> result; // global variation; set that store results that meet the criteria
vector<int> path; // store sigle result meet the criteria
void backtracking(int n, int k, int startIndex) {//backtrack with n k and startIndex as parameters; startIndex used to indicate the next recursion; incase repeat combination.
if (path.size() == k) {//terminate condition; save the path to form combination
result.push_back(path);//import path to result
return;
}
for (int i = startIndex; i <= n; i++) {//for loop to horizontal traverse
path.push_back(i); // save i(process path) to path
backtracking(n, k, i + 1); // recursion vertical traverse; next loop starts at i+1
path.pop_back(); // backtrack; withdraw the node that was dealed
}
}
public:
vector<vector<int>> combine(int n, int k) {//main function with n k
result.clear(); // clear result
path.clear(); // clear path
backtracking(n, k, 1);//recursion
return result;
}
};