320. Generalized Abbreviation

题目链接:https://leetcode.com/problems...

要输出所有的结果,backtracking标准思路。

public class Solution {
    public List<String> generateAbbreviations(String word) {
        List<String> result = new ArrayList();
        dfs(result, word, "", 0);
        return result;
    }
    
    private void dfs(List<String> result, String word, String curPath, int count) {
        // find one abbreviation
        if(word.length() == 0) {
            if(count > 0) curPath += count;
            result.add(curPath);
            return;
        }
        // 1. keep the current character
        dfs(result, word.substring(1), curPath + (count > 0 ? count : "") + word.charAt(0), 0);
        // 2. abbreviate as number
        dfs(result, word.substring(1), curPath, count + 1);
    }
}

bit也可以做,保留character为0,改为数字的为1,然后结果就是[0, 2^n]这么多,每个数学遍历一遍求对应的abbreviation即可。


lulouch13
13 声望6 粉丝