y******s 发帖数: 92 | 1 给一个array:[2, 3, 6],可以在里面插入: +, -, *, / 符号。求所有可能得到的值
。先不考虑被0除这些的特殊情况。
比如:
2+3+6=11
2*3+6=12 | l******s 发帖数: 3045 | 2 Thanks for sharing. A DFS solution.
private IList calculateAll(int[] nums){
ISet result = new HashSet();
if(nums.Length == 0) return result.ToList();
dfs(result, 0, nums[0], 0, nums);
return result.ToList();
}
private void dfs(ISet result, int total, int head, int iCur, int[] nums
){
if(iCur == nums.Length - 1){
result.Add(total + head);
return;
}
dfs(result, total + head, nums[iCur + 1], iCur + 1, nums); //+
dfs(result, total + head, -nums[iCur + 1], iCur + 1, nums); //-
dfs(result, total, head * nums[iCur + 1], iCur + 1, nums); //*
dfs(result, total, head / nums[iCur + 1], iCur + 1, nums); // div
} | y******s 发帖数: 92 | 3 太漂亮了!多谢!!
nums
【在 l******s 的大作中提到】 : Thanks for sharing. A DFS solution. : private IList calculateAll(int[] nums){ : ISet result = new HashSet(); : if(nums.Length == 0) return result.ToList(); : dfs(result, 0, nums[0], 0, nums); : return result.ToList(); : } : private void dfs(ISet result, int total, int head, int iCur, int[] nums : ){ : if(iCur == nums.Length - 1){
|
|