classCombinationIterator { voidbacktracking(vector<string>& results, string& current, int remain, const string& characters, int index){ if (remain == 0) { results.push_back(current); return; } if (index == characters.size()) { return; } if (remain > characters.size() - index) { return; } // add current.push_back(characters[index]); backtracking(results, current, remain - 1, characters, index + 1); current.pop_back(); // not add backtracking(results, current, remain, characters, index + 1); } vector<string> results; int index = 0; public: CombinationIterator(string characters, int combinationLength) { string current; backtracking(results, current, combinationLength, characters, 0); } string next(){ return results[index++]; } boolhasNext(){ return index < results.size(); } };
/** * Your CombinationIterator object will be instantiated and called as such: * CombinationIterator* obj = new CombinationIterator(characters, combinationLength); * string param_1 = obj->next(); * bool param_2 = obj->hasNext(); */
1289. Minimum Falling Path Sum II
和Minimum Falling Path Sum I一样,属于 DP 问题。
状态转移方程为: dp[row][column] = arr[row][column] + min(dp[row - 1][last_column] for last_column in [0, column_size) and last_column != column).
而且实现寻找上一层的最小值并不需要多一层循环,只需要保存上一层中最小值和次小值即可。