harrytothemoon / leetcodeAplus

Leetcode meeting note
2 stars 0 forks source link

[526] Beautiful Arrangement #77

Open harrytothemoon opened 3 years ago

harrytothemoon commented 3 years ago

runout

const permutator = (inputArr) => {
    let result = [];
    const permute = (arr, m = []) => {
        if (arr.length === 0) return result.push(m)
        for (let i = 0; i < arr.length; i++) {
            curr = arr.slice(),
            next = curr.splice(i, 1),
            permute(curr.slice(), m.concat(next))
        }
    }
   permute(inputArr)
   return result;
}

var countArrangement = function(n) {
    const ary = Array.from({length: n}, (v, i) => i + 1)
    let res = permutator(ary)
    return res.filter(d => d.every((c, i)=>(c % (i + 1) === 0) || ((i + 1) % c === 0))).length
};
tsungtingdu commented 3 years ago
var countArrangement = function(n) {
    let count = 0
    let arr = new Array(n).fill(0).map((_, index) => index + 1)
    recursion(arr, 0)
    return count

    function recursion(arr, index) {
        if (index === n) return count++

        for (let i = index; i < n; i++) {
            // try swap
            [arr[i], arr[index]] = [arr[index], arr[i]]
            // check
            if (check(index)) recursion(arr, index + 1)
            // swap back
            [arr[i], arr[index]] = [arr[index], arr[i]]
        }
    }

    function check(index) {
        if (arr[index] % (index + 1) === 0 || (index + 1) % arr[index] === 0) {
            return true
        }
        return false
    }
};