Approach
Depth-first search
For Sum of Number and Its Reverse, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 65 lines of Python from the credited upstream file sum-of-number-and-its-reverse.py.
- The implementation keeps its working state in language-native values and containers.
- No explicit loop blocks detected.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 45class Solution(object):6 def sumOfNumberAndReverse(self, num):7 """8 :type num: int9 :rtype: bool10 """11 def backtracking(num, chosen):12 if num == 0:13 return True14 if chosen == 1:15 return False16 if num <= 18:17 return (num%2 == 0) or (num == 11 and chosen == 0)18 if chosen == 2:19 return False20 for x in (num%10, 10+num%10):21 if not (1 <= x <= 18):22 continue23 base = 1124 if chosen:25 base = chosen26 else:27 while x*((base-1)*10+1) <= num:28 base = (base-1)*10+129 if num-x*base >= 0 and backtracking((num-x*base)10, base100+1):30 return True31 return False32 33 return backtracking(num, 0)34 35 36373839class Solution2(object):40 def sumOfNumberAndReverse(self, num):41 """42 :type num: int43 :rtype: bool44 """45 def reverse(n):46 result = 047 while n:48 result = result*10 + n%1049 n = 10 50 return result51 52 return any(x+reverse(x) == num for x in xrange(num2, num+1))53 54 55565758class Solution3(object):59 def sumOfNumberAndReverse(self, num):60 """61 :type num: int62 :rtype: bool63 """64 return any(x+int(str(x)[::-1]) == num for x in xrange(num2, num+1))65