|
| 1 | +想法:直接使用暴力解,找過所有可能的字串直到符合規則 |
| 2 | + |
| 3 | +Time Complexity : O(n^2 * n!) for there are O(n * n!) possible strings , and each one take O(n) to check |
| 4 | +Space Complexity : O(n!) for the recursion |
| 5 | + |
| 6 | + |
| 7 | +class Solution { |
| 8 | +public: |
| 9 | + long long int ans = 0 ; |
| 10 | + bool is_appeared(long long int now , int i) { |
| 11 | + while (now > 0) { |
| 12 | + if (now % 10 == i) |
| 13 | + return true ; |
| 14 | + now /= 10 ; |
| 15 | + } |
| 16 | + return false ; |
| 17 | + } |
| 18 | + bool constructnumber(string& pattern , int index ,long long int now) { |
| 19 | + if (index == pattern.length()) { |
| 20 | + ans = now ; |
| 21 | + return true ; |
| 22 | + } |
| 23 | + for(int i = 1 ; i < 10 ; i++) { |
| 24 | + if ( (( pattern[index] == 'I' && now % 10 < i ) || |
| 25 | + (pattern[index] == 'D' && now % 10 > i)) && !is_appeared(now , i)) { |
| 26 | + if ( constructnumber(pattern , index + 1 , now * 10 + i) ) |
| 27 | + return true ; |
| 28 | + } |
| 29 | + } |
| 30 | + return false ; |
| 31 | + } |
| 32 | + string smallestNumber(string pattern) { |
| 33 | + for(int startnumber = 1 ; startnumber < 10 ; startnumber++) { |
| 34 | + if ( constructnumber(pattern , 0 , startnumber) ) |
| 35 | + break ; |
| 36 | + } |
| 37 | + return to_string(ans) ; |
| 38 | + } |
| 39 | +}; |
| 40 | + |
| 41 | +// 法二:我們可以利用一個stack 紀錄我們將要加入的元素 |
| 42 | +(1)遇到 'D' : 加入現在的元素到 stack |
| 43 | +(2)遇到 'I' : 把所有元素都依序 pop 出並紀錄 |
| 44 | +可以想像成,當遇到 'I' 的時候,就可以確定前面的元素是必定符合規則且最小的,所以要 pop 出來 |
| 45 | + |
| 46 | +Time Complexity : O(n) for traversing the array and each number has been push , pop one times |
| 47 | +Space Complexity : O(n) for the stack to store n elements |
| 48 | + |
| 49 | +class Solution { |
| 50 | +public: |
| 51 | + string smallestNumber(string pattern) { |
| 52 | + string result; |
| 53 | + stack<int> numStack; |
| 54 | + |
| 55 | + // Iterate through the pattern |
| 56 | + for (int index = 0; index <= pattern.size(); index++) { |
| 57 | + // Push the next number onto the stack |
| 58 | + numStack.push(index + 1); |
| 59 | + |
| 60 | + // If 'I' is encountered or we reach the end, pop all stack elements |
| 61 | + if (index == pattern.size() || pattern[index] == 'I') { |
| 62 | + while (!numStack.empty()) { |
| 63 | + result += to_string(numStack.top()); |
| 64 | + numStack.pop(); |
| 65 | + } |
| 66 | + } |
| 67 | + } |
| 68 | + |
| 69 | + return result; |
| 70 | + } |
| 71 | +}; |
| 72 | + |
| 73 | + |
0 commit comments