Letter Combinations of a Phone Number
2014-08-19 12:48
330 查看
Given a digit string, return all possible letter combinations that the number could represent.
A mapping of digit to letters (just like on the telephone buttons) is given below.
A mapping of digit to letters (just like on the telephone buttons) is given below.
Input:Digit string "23" Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
代码:DFS
import java.util.*; public class Solution_14 { public static List<List<Integer>> threeSum(int[] num) { /* * int length = num.length; List<List<Integer>> result = new ArrayList<List<Integer>>(); List<Integer> tmp; for(int i = 0; i < length; i ++) for(int j = i + 1; j < length; j++) for(int k = j + 1; k < length; k++) if(num[i] + num[j] + num[k] == 0) { tmp = new ArrayList<Integer>(); tmp.add(num[i]); tmp.add(num[j]); tmp.add(num[k]); Collections.sort(tmp); if(!result.contains(tmp)) result.add(tmp); } return result; */ int length = num.length; Arrays.sort(num); List<List<Integer>> result = new ArrayList<List<Integer>>(); List<Integer> tmp; for(int i = 0; i < length; i ++) { if(i > 0 && num[i] == num[i - 1]) continue; int j = i + 1, k = length - 1; while(j < k) { if(j > i + 1 && num[j] == num[j - 1]) { j++; continue; } if(k < length - 1 && num[k] == num[k + 1]) { k--; continue; } int sum = num[i] + num[j] + num[k]; if(sum > 0) k--; else if(sum < 0) j++; else { tmp = new ArrayList<Integer>(); tmp.add(num[i]); tmp.add(num[j]); tmp.add(num[k]); result.add(tmp); j++; } } } return result; } public static void main(String[] args) { // TODO Auto-generated method stub int[] num = {0,0,0,0}; System.out.println(threeSum(num)); } }
相关文章推荐
- Leetcode:Letter Combinations of a Phone Number
- letter-combinations-of-a-phone-number
- Letter Combinations of a Phone Number
- LeetCode 17. Letter Combinations of a Phone Number
- LeetCode(17) Letter Combinations of a Phone Number
- Letter Combinations of a Phone Number--LeetCode
- [LeetCode] Letter Combinations of a Phone Number
- LeetCode--letter-combinations-of-a-phone-number
- [LeetCode] 17. Letter Combinations of a Phone Number
- [LeetCode] Letter Combinations of a Phone Number
- 个人记录-LeetCode 17. Letter Combinations of a Phone Number
- leetcode:Letter Combinations of a Phone Number
- 【LeetCode】Letter Combinations of a Phone Number
- [Leetcode]Letter Combinations of a phone number
- LeetCode之17----Letter Combinations of a Phone Number
- [LeetCode] Letter Combinations of a Phone Number
- leetcode 日经贴,Cpp code -Letter Combinations of a Phone Number
- LeetCode 17 Letter Combinations of a Phone Number
- [LeetCode]Letter Combinations of a Phone Number
- Letter Combinations of a Phone Number