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

[bug][javascript] permutations-ii #1567

Open
2 tasks done
Jayden12138 opened this issue Apr 15, 2024 · 1 comment
Open
2 tasks done

[bug][javascript] permutations-ii #1567

Jayden12138 opened this issue Apr 15, 2024 · 1 comment
Labels
help wanted Extra attention is needed

Comments

@Jayden12138
Copy link

请在提交 bug 之前先搜索

  • 我已经搜索过 issues,没有发现相同的 bug。

出错的题目链接

https://leetcode.cn/problems/permutations-ii/

报错信息

在文章回溯算法秒杀所有排列/组合/子集问题 - 排列-元素可重不可复选中,提到了一种剪枝思路,javascript代码部分如下图:

image

如果完全按照示例编写代码会有问题,报错信息如下

输入
nums = [1,1,2]
输出
[[1,2,1]]
预期结果
[[1,1,2],[1,2,1],[2,1,1]]

其中的preNum定义需要放在backTrack函数中,如果放在外层

image

如上图,会在连续的‘11’时也会判断为需要“剪枝”,预期结果中的[1, 1, 3]则不会被正确push到结果中

你是否愿意提交 PR 修复这个 bug?

  • 我愿意!
@Jayden12138 Jayden12138 added the help wanted Extra attention is needed label Apr 15, 2024
@Jayden12138
Copy link
Author

想pr,但是permutations-iisolution_code.md 中并没有找到对应的多语言解法,就直接在下面贴一下javascript的代码(AC)

image

/**
 * @param {number[]} nums
 * @return {number[][]}
 */
var permuteUnique = function(nums) {
	// 输入:nums = [1,1,2]
	// 输出:
	// [[1,1,2],
	// [1,2,1],
	// [2,1,1]]

	nums.sort((a, b) => a - b)

	let used = new Array(nums.length).fill(false)
	let resultList = []

	let temp = []

	function backTrack() {
		if (temp.length === nums.length) {
			resultList.push([...temp])
			return
		}

		let preSum = -999
		for (let i = 0; i < nums.length; i++) {
			if (used[i]) {
				continue
			}

			if (nums[i] === preSum) {
				continue
			}

			temp.push(nums[i])
			used[i] = true

			preSum = nums[i]

			backTrack()

			temp.pop()
			used[i] = false
		}
	}

	backTrack()

	return resultList
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
help wanted Extra attention is needed
Projects
None yet
Development

No branches or pull requests

1 participant