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

Leetcode 1079 活字印刷 回溯

时间:2021-04-20 15:41:31      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:public   ber   contain   img   idt   final   nbsp   return   ssi   

技术图片

  回溯解法,JAVA:

 public final int numTilePossibilities(String tiles) {
        Set<String> set = new HashSet<String>();
        search(tiles.toCharArray(), "", tiles.length(), set);
        return set.size();
    }

    public final void search(char[] chars, String ans, int len, Set<String> set) {
        if (len < 0) return;
        for (int i = 0; i < chars.length; i++) {
            if (chars[i] == ‘0‘) continue;
            char his = chars[i];
            chars[i] = ‘0‘;
            String next = ans + his;
            if (!set.contains(next)) set.add(next);
            search(chars, next, len - 1, set);
            chars[i] = his;
        }
    }

  JS:

/**
 * @param {string} tiles
 * @return {number}
 */
var numTilePossibilities = function (tiles) {
    let mySet = new Set();
    search(tiles.split(""), "", tiles.length, mySet);
    return mySet.size;
};

var search = function (arr, ans, len, mySet) {
    if (len < 0) return;
    for (let i = 0; i < arr.length; i++) {
        if (!arr[i]) continue;
        let his = arr[i];
        arr[i] = 0;
        mySet.add(ans + his);
        search(arr, ans + his, len - 1,mySet);
        arr[i] = his;
    }
}

 

Leetcode 1079 活字印刷 回溯

标签:public   ber   contain   img   idt   final   nbsp   return   ssi   

原文地址:https://www.cnblogs.com/niuyourou/p/14675079.html

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