[LeetCode-150 classic interview questions-day18]

Table of contents

17.Phone number alphabet

 77. Combination

46.Full arrangement 

52.N Queen Ⅱ 


 

17.Phone number alphabet

Question meaning:

Given a  2-9 string containing only numbers, return all letter combinations it can represent. Answers can be returned in  any order  .

The mapping of numbers to letters is given below (same as phone keys). Note that 1 does not correspond to any letters.

【Input example】digits="23"

【输出样例】["ad","ae","af","bd","be","bf","cd","ce","cf"]

class Solution {
    public List<String> letterCombinations(String digits) {
        List<String> ans = new ArrayList<String>();
        if(digits.length() == 0){
            return ans;
        }
        Map<Character,String> phoneMap = new HashMap<Character,String>(){
    
    {
            put('2',"abc");
            put('3',"def");
            put('4',"ghi");
            put('5',"jkl");
            put('6',"mno");
            put('7',"pqrs");
            put('8',"tuv");
            put('9',"wxyz");
        }};

        findString(ans,phoneMap,digits,0,new StringBuffer());
        return ans;
    }

    public void findString(List<String> ans, Map<Character,String> phoneMap,
    String digits,int index,StringBuffer curAns){
        if(index == digits.length()){
            //证明全部遍历完比
            ans.add(curAns.toString());
            //把找到的答案转成String类型存到列表中
        }else{
            char digit = digits.charAt(index);//取出字符,到map中获取对应的值
            String letters = phoneMap.get(digit);
            for(int i=0;i<letters.length();++i){
                curAns.append(letters.charAt(i));
                //递归调用,主要是用于找到下一位可能的字符
                findString(ans,phoneMap,digits,index+1,curAns);
                //递归回来进行回溯,把当前的字符删掉,寻找更多可能
                curAns.deleteCharAt(index);
            }
        }
    }
}

Time: Defeated 46.35%

Memory: Beaten by 26.39%

 77. Combination

Question meaning:

Given the sum of two integers  n ,  kreturn  [1, n] all possible  k combinations of numbers in the range.

You can return answers in  any order  .

【Input example】n=4,k=2

【Output sample】

[
  [2,4],
  [3,4],
  [2,3],
  [1,2],
  [1,3],
  [1,4],
]
class Solution {

    List<List<Integer>> ans = new ArrayList<List<Integer>>();
    
    public List<List<Integer>> combine(int n, int k) {
        findAns(1,n,k,new ArrayList<>());//从1开始找
        return ans;

    }
    public void findAns(int index,int n,int k,List<Integer> list){

        if(k == 0){
            //找到正确的答案,添加
            ans.add(new ArrayList<>(list));
            return;
        }
        for(int i=index;i<=n-k+1;++i){
            list.add(i);
            findAns(i+1,n,k-1,list);
            list.remove(list.size()-1);
        }
    }
}

Time: Beat 56.50%

Memory: Beaten by 5.94%

46.Full arrangement 

Question meaning:

Given an array without duplicate numbers  nums , return  all possible permutations  . You can  return answers in any order  .

[Input example] nums=[1,2,3]

[Output sample][[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2 ,1]]

Problem-solving ideas: recursive backtracking + hash table

1. Construct a hash map to store which numbers can currently be used and which numbers cannot be used;

2. The function of the recursive function is to find the number that can be at the index position. The number is located in the number, so the array is enumerated to obtain the value of the i-th position, and then a hash map is used to determine whether this number has been used. Pass. If it has been used, continue to search. If it has not been used, add it to the list, modify the flag, and continue to search for the index+1 position;

3. When backtracking, in addition to moving the last digit, you also need to re-modify the flag.

class Solution {
    List<List<Integer>> ans = new ArrayList<List<Integer>>();
    
    public List<List<Integer>> permute(int[] nums) {
        //构造map,初始化所有数字现在都可以用
        int len = nums.length;
        Map<Integer,Boolean> useMap= new HashMap<Integer,Boolean>();
        for(int i=0;i<len;++i){
            useMap.put(nums[i],true);
        }
        searchOrder(1,nums,len,useMap,new ArrayList<>());//从第一位开始找
        return ans;
    }

    public void searchOrder(int index,int[] nums,int len,Map<Integer,Boolean> useMap,List<Integer> list){
        if(index == len+1){
            //找到正确的答案,添加
            ans.add(new ArrayList<>(list));
            return;
        }
        for(int i=0; i < len;++i){
            //从第一位到最后一位,可以选择那一些
            int num = nums[i];
            if(useMap.get(num) == true){
                list.add(num);
                //修改标志位
                useMap.put(num,false);
                searchOrder(index+1,nums,len,useMap,list);
                list.remove(list.size()-1);
                useMap.put(num,true);
            }
        }
    }
}

Time: Defeated 78.23%

Memory: Beaten by 48.52% 

52.N Queen Ⅱ 

Question meaning:

n The queen problem  studies how to  n place queens  n × n on a chessboard so that the queens cannot attack each other.

Gives you an integer  n that returns   the number of different solutions to the n-queens problem .

【Input sample】n=4

[Output sample] 2

Problem-solving ideas: recursive backtracking + Boolean array

Why !row[i] && !dia[index-i+n] && !assDia[index+i]?

row[i]: easy to understand, the same column already has a value

But, why are the values ​​in dia and assDia written like this?

 

class Solution {
    int ans = 0;
    
    public int totalNQueens(int n) {
        //n皇后问题
        //任意两个皇后不能在同一横轴,纵轴,对角线上
        //三个数组,表示当前纵轴,正对角线,副对角线上是否有值,默认false
        boolean[] row = new boolean[n+1];
        boolean[] dia = new boolean[2*n+1];
        boolean[] assDia = new boolean[2*n+1];
        search(1,n,row,dia,assDia);//从第一行开始判断
        
        return ans;
    }

    private void search(int index,int n, boolean[] row, boolean[] dia, boolean[] assDia){
        if(index == n+1){
            ++ans;
            return;
        }
        //index表示当前查找第几行,所以遍历遍历列就可以了
        for(int i=1;i<=n;i++){
            if(!row[i] && !dia[index-i+n] && !assDia[index+i]){
                row[i] = dia[index-i+n] = assDia[index+i] = true;//已经有值
                search(index+1,n,row,dia,assDia);
                //回溯
                row[i] = dia[index-i+n] = assDia[index+i] = false;
                
            }
        }
    }
}

Time: Beat 100.00%

Memory: Beaten by 74.08% 

Guess you like

Origin blog.csdn.net/qq_37998848/article/details/132582902