320 Generalized Abbreviation

public class Solution {
    public List<String> generateAbbreviations(String word) {
        List<String> res = new ArrayList<String>();
        backtrack(res, word, 0, "", 0);
        return res;
    }
    
    public void backtrack(List<String> res, String word, int pos, String abbr, int count){
        if(pos == word.length()){
            if(count > 0) abbr += count;
            res.add(abbr);
        } else {
            backtrack(res, word, pos+1, abbr, count+1);   // 变成数字
            backtrack(res, word, pos+1, abbr + (count > 0 ? count : "") + word.charAt(pos), 0);  // 保留
        }
    }
}

22 Generate Parentheses

public class Solution {
    public List<String> generateParenthesis(int n) {
        List<String> res = new ArrayList<String>();
        dfs(res, "", n, 0);
        return res;
    }
    
    // n represent "(",  m represent ")"
    public void dfs(List<String> res, String path, int n, int m){
        if(n == 0 && m == 0){
            res.add(path);
            return;
        }
        
        if(n > 0){
            dfs(res, path + "(", n-1, m+1);
        }
        
        if(m > 0){
            dfs(res, path  + ")", n, m-1);
        }
    }
}

大米中的大米
12 声望5 粉丝

你的code是面向面试编程的,收集和整理leetcode discussion里个人认为的最优且最符合我个人思维逻辑的解法。