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 }

 

你可能感兴趣的:(G面经prepare: X-Straight)