第七章 回溯演算法part01
77. 組合 216.組合總和III 17.電話號碼的字母組合
77. 組合
題目連結 :
Code ( 用 遞迴 模擬 迴圈 ) :
class Solution {
public:
vector<vector<int>> combine(int n, int k) {
vector<int> vec_Temp_Cache_For_RecordNum ;
vector<vector<int>> vec_2_Dimention_For_Receive_And_Return ;
work_Recursino_For_forLoop( 1 , 1 , n , k , vec_Temp_Cache_For_RecordNum , vec_2_Dimention_For_Receive_And_Return ) ;
return vec_2_Dimention_For_Receive_And_Return ;
}
void work_Recursino_For_forLoop( int i_Work_In , int i_Layer , int n , int k , vector<int> & vec_Temp_Cache_For_RecordNum , vector<vector<int>> & vec_2_Dimention_For_Receive_And_Return )
{
if(i_Layer != k ) // 邏輯 性 / 安全 性 / 效率
{
for( int i = i_Work_In; i <= (( n - k ) + i_Layer ) ; i++ )
{
//vec_Temp_Cache_For_RecordNum[ (i_Layer - 1 ) ] = i ;
vec_Temp_Cache_For_RecordNum.push_back(i) ;
work_Recursino_For_forLoop( (i + 1 ) , ( i_Layer + 1 ) , n , k , vec_Temp_Cache_For_RecordNum , vec_2_Dimention_For_Receive_And_Return ) ;
vec_Temp_Cache_For_RecordNum.pop_back() ;
}
}
else
{
for( int i = i_Work_In; i <= (( n - k ) + i_Layer ) ; i++ )
{
//vec_Temp_Cache_For_RecordNum[ (i_Layer - 1 ) ] = i ;
vec_Temp_Cache_For_RecordNum.push_back(i) ;
vec_2_Dimention_For_Receive_And_Return.push_back(vec_Temp_Cache_For_RecordNum ) ;
//work_Recursino_For_forLoop( (i + 1 ) , ( i_Layer + 1 ) , n , k )
vec_Temp_Cache_For_RecordNum.pop_back() ;
}
}
}
};
216.組合總和III
題目連結 :
Code ( 遞迴 遍歷 , 回溯 , 不斷 地 更新 Cache 向量 中 的 值 , Cache Sum ) :
class Solution {
public:
vector<vector<int>> combinationSum3(int k, int n) {
int target = n ;
vector<int> vec_Temp_Cache_For_NumSequence ;
vector<vector<int>> vec_2_Dimention_For_Receive_And_Return ;
int num_Cache_Sum = 0 ;
// 嘗試 遞迴 遍歷
fuction_Work_Recursion_For_forLoop(1 , 1 , k , target , vec_Temp_Cache_For_NumSequence , vec_2_Dimention_For_Receive_And_Return , num_Cache_Sum ) ;
return vec_2_Dimention_For_Receive_And_Return ;
}
void fuction_Work_Recursion_For_forLoop( int i_Work_In , int i_Layer , int k , int target , vector<int> & vec_Temp_Cache_For_NumSequence , vector<vector<int>> & vec_2_Dimention_For_Receive_And_Return , int & num_Cache_Sum )
{ // “ 省 記憶體 ” , Question : 會 省 暫存器 嗎 ? // 程式碼 會不會 自動 地 進行 相關 最佳化
if( i_Layer != k )
{
for( int i = i_Work_In ; i <= (( 9 - k ) + i_Layer ) ; i++ )
{
num_Cache_Sum += i ;
vec_Temp_Cache_For_NumSequence.push_back(i) ;
//
fuction_Work_Recursion_For_forLoop( ( i + 1 ) , ( i_Layer + 1 ) , k , target , vec_Temp_Cache_For_NumSequence , vec_2_Dimention_For_Receive_And_Return , num_Cache_Sum ) ;
num_Cache_Sum -= i ;
vec_Temp_Cache_For_NumSequence.pop_back() ;
}
}
else
{
for( int i = i_Work_In ; i <= (( 9 - k ) + i_Layer ) ; i++ )
{
num_Cache_Sum += i ;
vec_Temp_Cache_For_NumSequence.push_back(i) ;
//