You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

LeetCode 131解法中list = new List<string>(list)的作用是什么?

LeetCode 131 回文分割 C#解法及问题解答

解法代码

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

    void CheckSubstring(List<string> list, string s, IList<IList<string>> res, int startIndex)
    {
        if (startIndex == s.Length)
        {
            list = new List<string>(list);
            res.Add(list);
            return;
        }
        for (int end = startIndex; end < s.Length; end++)
        {
            string sub = s.Substring(startIndex, end - startIndex + 1);
            if (IsPalindrome(sub))
            {
                list.Add(sub);
                CheckSubstring(list, s, res, end + 1);
                list.RemoveAt(list.Count - 1);
            }
        }
    }

    bool IsPalindrome(string s)
    {
        int left = 0, right = s.Length - 1;
        while (left < right)
        {
            if (s[left] != s[right])
            {
                return false;
            }
            left++;
            right--;
        }
        return true;
    }
}

问题解答

你说的没错,这行代码确实是创建原列表的副本,这么做的核心原因是回溯过程中我们复用了同一个list对象:

在整个递归回溯流程里,我们会不断给list添加回文子串,递归结束后又会删除最后添加的元素(也就是list.RemoveAt(list.Count - 1)这步),以此尝试不同的分割组合。如果直接把原list加到res里,res中保存的其实是这个list对象的引用——后续的删除操作会直接修改res里已经存进去的列表内容,最后所有结果都会变成空或者错误状态。

而通过new List<string>(list)创建副本后,我们把这个独立的新列表加到res里,它的内容就固定下来了,不会再被后续回溯操作修改,这样res里才能保存正确的分割结果。

内容的提问来源于stack exchange,提问作者Liu_064

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 02:10:19