93.复原IP地址
class Solution {
public : vector< string> result; bool isValid ( const string& s, int start, int end) { if ( start > end) { return false ; } if ( s[ start] == '0' && start != end) { return false ; } int num = 0 ; for ( int i= start; i<= end; i++ ) { if ( s[ i] > '9' || s[ i] < '0' ) { return false ; } num = num * 10 + ( s[ i] - '0' ) ; if ( num > 255 ) { return false ; } } return true ; } void BackTracking ( string& s, int startIndex, int pointNum) { if ( pointNum == 3 ) { if ( isValid ( s, startIndex, s. size ( ) - 1 ) ) { result. push_back ( s) ; } return ; } for ( int i= startIndex; i< s. size ( ) ; i++ ) { if ( isValid ( s, startIndex, i) ) { s. insert ( s. begin ( ) + i+ 1 , '.' ) ; pointNum++ ; BackTracking ( s, i+ 2 , pointNum) ; pointNum-- ; s. erase ( s. begin ( ) + i+ 1 ) ; } else break ; } } vector< string> restoreIpAddresses ( string s) { result. clear ( ) ; if ( s. size ( ) < 4 || s. size ( ) > 12 ) return result; BackTracking ( s, 0 , 0 ) ; return result; }
} ;
78.子集
class Solution {
public : vector< vector< int >> result; vector< int > path; void BackTracking ( vector< int > & nums, int index) { result. push_back ( path) ; if ( index >= nums. size ( ) ) { return ; } for ( int i= index; i< nums. size ( ) ; i++ ) { path. push_back ( nums[ i] ) ; BackTracking ( nums, i+ 1 ) ; path. pop_back ( ) ; } } vector< vector< int >> subsets ( vector< int > & nums) { result. clear ( ) ; path. clear ( ) ; BackTracking ( nums, 0 ) ; return result; }
} ;
90.子集II
class Solution {
public : vector< vector< int >> result; vector< int > path; void BackTracking ( vector< int > & nums, int index) { result. push_back ( path) ; if ( index >= nums. size ( ) ) { return ; } for ( int i= index; i< nums. size ( ) ; i++ ) { path. push_back ( nums[ i] ) ; BackTracking ( nums, i+ 1 ) ; path. pop_back ( ) ; } } vector< vector< int >> subsets ( vector< int > & nums) { result. clear ( ) ; path. clear ( ) ; sort ( nums. begin ( ) , nums. end ( ) ) ; BackTracking ( nums, 0 ) ; return result; }
} ;