您的位置:首页 > 其它

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.



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));
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: