C# - recursive backtracking with char array


  • 0
        public IList<string> FindStrobogrammatic(int n) 
        {
            IList<string> list = new List<string>();
            Find(list, new char[n], 0, n - 1);
            return list;
        }
        
        public void Find(IList<string> list, char[] curr, int left, int right)
        {
            if (left > right)
            {
                list.Add(new string(curr));
            }
            else if (left == right)
            {
                curr[left] = '0';
                list.Add(new string(curr));
                
                curr[left] = '1';
                list.Add(new string(curr));
                
                curr[left] = '8';
                list.Add(new string(curr));
            }
            else
            {
                if (left > 0)
                {
                    curr[left] = '0';
                    curr[right] = '0';
                    Find(list, curr, left + 1, right - 1);
                }
                
                curr[left] = '1';
                curr[right] = '1';
                Find(list, curr, left + 1, right - 1);
                
                curr[left] = '6';
                curr[right] = '9';
                Find(list, curr, left + 1, right - 1);
                
                curr[left] = '9';
                curr[right] = '6';
                Find(list, curr, left + 1, right - 1);
                
                curr[left] = '8';
                curr[right] = '8';
                Find(list, curr, left + 1, right - 1);
            }
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.