码迷,mamicode.com
首页 > 其他好文 > 详细

Telephone Number

时间:2014-11-21 06:54:39      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   ar   color   os   sp   for   strong   

Problem

Print all valid phone numbers of length n subject to following constraints:
If a number contains a 4, it should start with 4
No two consecutive digits can be same
Three digits (e.g. 7,2,9) will be entirely disallowed, take as input

Solution

Recursive + DFS

 1 public static List<List<Integer>> generateNumber(int length, List<Integer> baned) {
 2     List<List<Integer>> res = new ArrayList<List<Integer>>();
 3     List<Integer> num = new ArrayList<Integer>();
 4     HashSet<Integer> ban = new HashSet<Integer>();
 5     for(int i=0; i<baned.size(); i++) {
 6         ban.add(baned.get(i));
 7     }
 8     
 9     helper(res, num, ban, -1, length, 0);
10     
11     return res;
12 }
13 
14 public static void helper(List<List<Integer>> res, List<Integer> num, HashSet<Integer> ban, int prev, int length, int pos) {
15     if(pos == length) {
16         res.add(new ArrayList<Integer>(num));
17         return;
18     }
19     
20     for(int i=0; i<=9; i++) {
21         if(pos != 0 && i == 4) continue; 
22         else if(ban.contains(i)) continue;
23         else if(i == prev) continue;
24         
25         num.add(i);
26         helper(res, num, ban, i, length, pos+1);
27         num.remove(num.size()-1);
28     }
29 }

 

Telephone Number

标签:style   blog   io   ar   color   os   sp   for   strong   

原文地址:http://www.cnblogs.com/superbo/p/4111919.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!