leetcode131

深度优先遍历(DFS),先判断前一个部分是否是回文,如果是,则将其加进集合中,然后继续判断后面的回文串。

在回溯的时候,将之前加入集合的串删除,重新选择回文串。每到达一次叶子节点,得到一组结果。

public class Solution
    {
        IList<IList<string>> res = new List<IList<string>>();
        public IList<IList<string>> Partition(string s)
        {
            DFS(s, new List<string>());
            return res;
        }

        private void DFS(string s, List<string> list)
        {
            if (s.Length < 1)
            {
                res.Add(new List<string>(list));
                return;
            }
            for (int i = 1; i <= s.Length; i++)
            {
                string str = s.Substring(0, i);
                if (isPalindrom(str))
                {
                    list.Add(str);
                    DFS(s.Substring(i), list);
                    list.RemoveAt(list.Count - 1);
                }
                else
                {
                    continue;
                }
            }
        }
        private bool isPalindrom(String s)
        {       //s必须是》=1的字符串        
            int p1 = 0;
            int p2 = s.Length - 1;
            int len = (s.Length + 1) / 2;
            for (int i = 0; i < len; i++)
            {
                if (s[p1++] != s[p2--])
                {
                    return false;
                }
            }
            return true;
        }
    }

猜你喜欢

转载自www.cnblogs.com/asenyang/p/9745997.html