LeetCode 17 phone number letter combination (search) & 18 sum of four numbers

Letter combination of phone number

Title description

Given a string containing only numbers 2-9, return all letter combinations it can represent.
The mapping of numbers to letters is given as follows (same as phone buttons). Note that 1 does not correspond to any letters.

Example:

Input: “23”
Output: [“ad”, “ae”, “af”, “bd”, “be”, “bf”, “cd”, “ce”, “cf”].

Description:

Although the answers above are in lexicographical order, you can choose the order in which the answers are output.

This kind of problem is obviously a search problem. You can use breadth-first search bfs, store strings in a queue for operations, or use depth-first search.

Depth-first search is used here. When using dfs, we usually use recursion to achieve, and recursion is a backtracking process. You can create a new string every time but you can also use StringBuilder for reuse. For phone numbers, you need to pre-store, you can use HashMap or List [] array to complete.

The specific code is:

 List<String>value=new ArrayList<String>();
	 String digitString;
	 List<Character> list[];
	public  List<String> letterCombinations(String digits) {
    
    
		if(digits==null||"".equals(digits))return value;
		digitString=digits;
		list=new ArrayList[8];
		//初始化
		for(int i=0;i<list.length;i++)
		{
    
    
			list[i]=new ArrayList<Character>();
		}
		for(int i=0;i<5;i++)
		{
    
    
        	for(int j=0;j<3;j++)
        	{
    
    
        		list[i].add((char) ('a'+i*3+j));
        	}
            
		}
		list[5].add('p');list[5].add('q');list[5].add('r');list[5].add('s');
		list[6].add('t');list[6].add('u');list[6].add('v');
		list[7].add('w');list[7].add('x');list[7].add('y');list[7].add('z');
		
		
		dfs(new StringBuilder(""),0);
		
//		for(List<Character> a:list)//打印测试
//		{
    
    
//			System.out.println(a.toString());
//		}
		return value;
		
    }
	private  void dfs(StringBuilder stringBuilder, int index) {
    
    
		if(index==digitString.length()) 
		{
    
    value.add(stringBuilder.toString());return;}
		int va=digitString.charAt(index)-'2';
		for(int i=0;i<list[va].size();i++)
		{
    
    
			
			dfs(stringBuilder.append(list[va].get(i)), index+1);
			stringBuilder.deleteCharAt(index);
		}	
	}

Insert picture description here

Sum of four

description

Given an array nums containing n integers and a target value target, judge whether there are four elements a, b, c, and d in nums such that the value of a + b + c + d is equal to target? Find all four-tuples that meet the conditions and do not repeat.

note:

The answer cannot contain repeated quadruples.

Example:

Given the array nums = [1, 0, -1, 0, -2, 2], and target = 0.
The set of quadruples that meet the requirements are:
[
[-1, 0, 0, 1],
[-2, -1, 1, 2],
[-2, 0, 0, 2]
]

Analysis, we did the sum of three numbers earlier . Here the sum of four numbers also uses a relatively similar method.

The sum of three numbers can circulate a layer of i, then left and right double pointers from the right to the middle.
Insert picture description here

Analysis The
sum of four numbers can be converted to the sum of three numbers. a+b+c+d=targetThat is a+b+c=target-d.
In the specific implementation, sort first , only need to traverse i, j and then use left and right double pointers. Double pointers can reduce a layer of loops, making the final complexity O(n3);
Insert picture description here

The specific implementation also needs to consider the same details such as deduplication:

  • Skip when nums[i]==nums[i-1], because the number has been the leftmost.
  • nums[j]==nums[j-1] is skipped because the number has been the second number.
  • When nums[i]+nums[j]+nums[left]+nums[right]==target, left should go to the right until it is different from the right side, and right should go to the left until it is different from the left side (excluding the same situation).
  • Pruning optimization , filtering some impossible situations at the beginning, returning the result directly to reduce calculation .

See the code in detail for other details. The ac code is:

public List<List<Integer>> fourSum(int[] nums, int target) {
    
    
        Arrays.sort(nums);
		 List<List<Integer>> list = new ArrayList<List<Integer>>();
		 if(nums.length<4)return list;
		 if(nums[nums.length-1]+nums[nums.length-2]+nums[nums.length-3]+nums[nums.length-4]<target)return list;	
		 for(int i=0;i<nums.length-3;i++)
		 {
    
    
			 if(i>0&&nums[i]==nums[i-1]) {
    
    continue;}//去重,这种情况不需要
			 if(nums[i]+nums[i+1]+nums[i+2]+nums[i+3]>target) return list;//过滤不可能满足的
			 for(int j=i+1;j<nums.length-2;j++)
			 {
    
    
				 if(j>i+1&&nums[j]==nums[j-1]) {
    
    continue;}//去重,这种情况不需要
				 if(nums[i]+nums[j]+nums[j+1]+nums[j+2]>target)break;//过滤不可能满足的
				 int left=j+1; int right=nums.length-1;
				 while (left<right) {
    
     
					int sum=nums[i]+nums[j]+nums[left]+nums[right];
					if(nums[i]+nums[j]+nums[left]+nums[left+1]>target)break;
					if(sum==target)
					{
    
    
						while (left<nums.length-1&&nums[left]==nums[left+1]) {
    
    left++;}
						while (right>0&&nums[right]==nums[right-1]) {
    
    right--;}
						List<Integer>list2=new ArrayList<Integer>();
						list2.add(nums[i]);list2.add(nums[j]);
						list2.add(nums[left]);list2.add(nums[right]);
						list.add(list2);
					}
					if(left>right)break;
					if(sum>target)
					{
    
    
						right--;
					}
					else {
    
    
						left++;
					}					
				}
			 }
		 }
		 return list;
    }

Insert picture description here

As for other methods and optimizations, welcome to share, search on WeChat bigsai, reply to the group and check in together.

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_40693171/article/details/108342362