Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

46. Permutations #131

Open
Tcdian opened this issue Apr 25, 2020 · 1 comment
Open

46. Permutations #131

Tcdian opened this issue Apr 25, 2020 · 1 comment

Comments

@Tcdian
Copy link
Owner

Tcdian commented Apr 25, 2020

46. Permutations

给定一个 没有重复 数字的序列,返回其所有可能的全排列。

Example

Input: [1,2,3]
Output:
[
  [1,2,3],
  [1,3,2],
  [2,1,3],
  [2,3,1],
  [3,1,2],
  [3,2,1]
]
@Tcdian
Copy link
Owner Author

Tcdian commented Apr 25, 2020

Solution

  • JavaScript Solution
/**
 * @param {number[]} nums
 * @return {number[][]}
 */
var permute = function(nums) {
    const result = [];
    const cache = new Set();
    backtracking();
    return result;

    function backtracking() {
        if (cache.size === nums.length) {
            result.push([...cache]);
            return;
        }
        for (let i = 0; i < nums.length; i++) {
            if (!cache.has(nums[i])) {
                cache.add(nums[i]);
                backtracking();
                cache.delete(nums[i]);
            }
        }
    }
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant