Skip to content

Commit ee62ab3

Browse files
committed
combination sumS solved. easy with dfs. But:
may need to learn how to deal with the order of strings.
1 parent d661b82 commit ee62ab3

File tree

3 files changed

+84
-0
lines changed

3 files changed

+84
-0
lines changed

combination_sum.rb

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
def combination_sum(candidates, target)
2+
result=Array.new
3+
dfs(candidates, Array.new, 0, target, result)
4+
result.each {|re| re.sort!}
5+
result.sort
6+
end
7+
8+
def dfs(nums, tmpNums, curSum, target, result)
9+
if target==curSum
10+
result.push tmpNums
11+
return
12+
else
13+
for i in 0..nums.size-1
14+
if target>=curSum+nums[i]
15+
tmpNumsNew=tmpNums.dup
16+
tmpNumsNew.push nums[i]
17+
dfs(nums[i..-1], tmpNumsNew, curSum+nums[i], target, result)
18+
end
19+
end
20+
end
21+
end
22+
23+
ar=2, 3, 6, 7
24+
p combination_sum ar, 7
25+
ar=[8,7,4,3]
26+
p combination_sum ar, 11
27+

combination_sum2.rb

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
def combination_sum2(candidates, target)
2+
result=Array.new
3+
dfs(candidates, Array.new, 0, target, result)
4+
result.sort!
5+
result.uniq #Should I use uniq methed or implement this method?
6+
end
7+
8+
def dfs(nums, tmpNums, curSum, target, result)
9+
for i in 0..nums.size-1
10+
if target==curSum+nums[i]
11+
tmpNumsNew=tmpNums.dup
12+
tmpNumsNew.push nums[i]
13+
result.push tmpNumsNew.sort
14+
elsif target>curSum+nums[i]
15+
tmpNumsNew=tmpNums.dup
16+
tmpNumsNew.push nums[i]
17+
break if i==nums.size-1
18+
dfs(nums[i+1..-1], tmpNumsNew, curSum+nums[i], target, result)
19+
end
20+
end
21+
end
22+
23+
ar=2, 3, 6, 7
24+
p combination_sum ar, 7
25+
ar=[8, 7, 4, 3]
26+
p combination_sum ar, 11
27+
ar=10, 1, 2, 7, 6, 1, 5
28+
p combination_sum ar, 8

combination_sum3.rb

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
def combination_sum3(k,target)
2+
result=Hash.new
3+
dfs([1,2,3,4,5,6,7,8,9], Array.new, 0, target, result)
4+
res=Array.new
5+
result.each{|key,v| res.push key if v==true&&key.size==k}
6+
res.sort
7+
end
8+
9+
def dfs(nums, tmpNums, curSum, target, result)
10+
for i in 0..nums.size-1
11+
if target==curSum+nums[i]
12+
tmpNumsNew=tmpNums.dup
13+
tmpNumsNew.push nums[i]
14+
result[tmpNumsNew.sort]=true
15+
elsif target>curSum+nums[i]
16+
tmpNumsNew=tmpNums.dup
17+
tmpNumsNew.push nums[i]
18+
break if i==nums.size-1
19+
dfs(nums[i+1..-1], tmpNumsNew, curSum+nums[i], target, result)
20+
end
21+
end
22+
end
23+
24+
ar=2, 3, 6, 7
25+
p combination_sum3 3,7
26+
ar=[8, 7, 4, 3]
27+
p combination_sum3 3,11
28+
ar=10, 1, 2, 7, 6, 1, 5
29+
p combination_sum3 3,8

0 commit comments

Comments
 (0)