Telephone Number

本文介绍了一种使用递归加深度优先搜索(DFS)的方法来生成所有长度为n的有效电话号码。这些电话号码需要遵循特定的规则:如果包含数字4,则必须以4开头;不允许出现连续相同的数字;某些特定的三位数组合被禁止。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 }

 

转载于:https://www.cnblogs.com/superbo/p/4111919.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值