zoukankan      html  css  js  c++  java
  • G面经prepare: X-Straight

    Define “X-Straight” as X cards with consecutive numbers (X >= 3). Determine if the deck can be fully divided into sets of “X-Straight”.
    Example: 1, 2, 3, 4, 4, 5, 6 -> True

    Backtracking:

     1 package Straight;
     2 import java.util.*;
     3 
     4 public class Solution2 {
     5     HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
     6     public boolean determine(int[] arr) {
     7         for (int elem : arr) {
     8             if (!map.containsKey(elem)) {
     9                 map.put(elem, 1);
    10             }
    11             else map.put(elem, map.get(elem)+1);
    12         }
    13         return helper(arr, 0);
    14     }
    15     
    16     public boolean helper(int[] arr, int pos) {
    17         if (pos == arr.length) return true;
    18         int cur = arr[pos];
    19         for (int k=3; k<map.keySet().size(); k++) {
    20             HashMap<Integer, Integer> copy = new HashMap<Integer, Integer>(map);
    21             for (int i=cur; i<cur+k; i++) {
    22                 if (!map.containsKey(i)) return false;
    23                 if (map.get(i) == 0) return false;
    24                 map.put(i, map.get(i)-1);
    25             }
    26             while (pos<arr.length && map.get(arr[pos]) == 0) pos++;
    27             if (helper(arr, pos))
    28                 return true;
    29             map = copy;
    30         }
    31         return false;
    32         
    33     }
    34 
    35     /**
    36      * @param args
    37      */
    38     public static void main(String[] args) {
    39         // TODO Auto-generated method stub
    40         Solution2 sol = new Solution2();
    41         boolean res = sol.determine(new int[]{1,2,3,2,3,4,8,9,10,6});
    42         if (res) System.out.println("true");
    43         else System.out.println("false");
    44     }
    45 
    46 }
  • 相关阅读:
    团队冲刺-1
    最优惠购买书籍
    gogoing软件NABCD
    二维数组首尾相连
    首尾相连一维数组的最大子数组和
    二维数组返回最大子矩阵之和
    石家庄铁道大学基础教学楼电梯使用调查
    子数组最大值求和
    返回一个整数数组中最大子数组的和-课堂训练(子数组为连续)
    软件工程概论-四则运算
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/5134879.html
Copyright © 2011-2022 走看看