Java AC
public class Solution { public ArrayList<ArrayList<Integer>> combine(int n, int k) { ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>(); ArrayList<Integer> numList = new ArrayList<Integer>(); dfs(list, numList, n, k, 1); return list; } public void dfs(ArrayList<ArrayList<Integer>> list, ArrayList<Integer> numList, int n, int k, int start){ if(numList.size() == k){ list.add(new ArrayList<Integer>(numList)); return; } for(int i = start; i <= n; i++){ numList.add(i); dfs(list, numList, n, k, i+1); numList.remove(numList.size()-1); } } }2、Letter Combinations of a Phone Number Total Accepted: 6921 Total Submissions: 27334 My Submissions
Java AC
public class Solution { public String array[] = {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"}; public ArrayList<String> letterCombinations(String digits) { ArrayList<String> list = new ArrayList<String>(); if(digits == null){ return list; } char numArr[] = digits.toCharArray(); int len = digits.length(); StringBuffer sb = new StringBuffer(); dfs(list,sb,0,numArr,len); return list; } public void dfs(ArrayList<String> list,StringBuffer sb, int tempLen,char numArr[],int len){ if(tempLen == len){ list.add(sb.toString()); return; } if(numArr[tempLen] >= '0' && numArr[tempLen] <= '9' ){ String tempStr = array[numArr[tempLen] - '0']; int strLen = tempStr.length(); for(int i = 0; i < strLen; i++){ StringBuffer newsb = new StringBuffer(sb); newsb.append(String.valueOf(tempStr.charAt(i))); dfs(list,newsb,tempLen+1,numArr,len); } }else{ StringBuffer newsb = new StringBuffer(sb); newsb.append(String.valueOf(numArr[tempLen])); dfs(list,newsb,tempLen+1,numArr,len); } } }