Why i get a wa with "3"? In runcode, it's correct


  • 0
    N
    #include <vector>
    #include <string>
    
    using std::string;
    using std::vector;
    
    string dig[8] = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
    
    vector<string> ans;
    
    class Solution {
    public:
    	void dfs(string str, string digits) {
    		if (digits == "") {
    			ans.push_back(str);
    			return;
    		}
    		int num = digits[0] - '2';
    		for (size_t i=0; i<dig[num].size(); ++i) {
    			dfs(str + dig[num][i], digits.substr(1));
    		}
    	}
    
        vector<string> letterCombinations(string digits) {
    		if (digits == "") return ans;
    		dfs("", digits);
    		return ans;
        }
    };

  • 2
    T

    It's the "usual", see https://leetcode.com/faq/#different-output

    Because the judger executes all test cases using the same program instance, global/static variables affect the program state from one test case to another.

    Consider this amendment:

    vector<string> letterCombinations(string digits) {
        ans.clear(); // added
        if (digits == "") return ans;
        dfs("", digits);
        return ans;
    }

Log in to reply
 

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