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);
}
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。